Can Java's ternary/conditional operator (?:) be used to call methods instead of assigning values?

前端 未结 3 657
执念已碎
执念已碎 2020-11-30 08:38

In pages like http://en.wikipedia.org/wiki/?: the ternary/conditional operator ?: seems to be used for conditional assignments. I tried to use it for method cal

3条回答
  •  一个人的身影
    2020-11-30 09:26

    The ternary operator is simply syntactic sugar.
    It makes code easier to read/write, but it does not add real functionality.
    Its primary use was to compress several lines of code into a single line, and was very useful when building Strings that differ only slightly, based on some conditions.

    eg.

    Collection col = ...
    System.out.println("There " + (col.size()==1 ? "is" : "are") + " "
         + col.size() + " " + (col.size()==1 ? "element" : "elements")
         + " in the collection");
    

    instead of

    Collection col = ...
    String message = "There ";
    if(col.size()==1)
        message += "is";
    else
        message += "are";
    message += " "+col.size()
    if(col.size()==1)
        message += " element";
    else
        message += " elements";
    message += " in the collection";
    System.out.println(message);
    

    As you can see, it simplifies the code.
    (note: In the second example it is better to use StringBuilder instead of String concatenation)

    But since (condition) ? doThis() : doThat(); (without return values) has the same meaning as if(condition) doThis(); else doThat(); there would be two ways of writing the same thing, without adding functionality. It would only complicate things:

    • for programmers: code is not uniform
    • for the implementation of the ternary operator: it now has to also support void methods

    So No, the ternary operation can not be used for conditional method calling. Use if-else instead:

    if(condition)
        doThis();
    else
        doThat(); 
    

提交回复
热议问题