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

前端 未结 3 654
执念已碎
执念已碎 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:23

    The ternary (conditional) operator returns a value. If your methods don't, they can't be used as parts of the operator (where it takes the value).

    In order to understand it better, let's think of one simple binary operator: +. It works this way:

     +   -->  
    

    It needs of 2 evaluable parts, and returns another. If you typed

    doThis() + doThat();
    

    or even

    gimmeAValue = doThis() + doThat();
    

    it would fail, as neither doThis() nor doThat() evaluate to anything (they "return" void). Of course, both and must be of some "compatible" type in order the + operator can handle them and return a value of some type.

    Now let's see the ternary operator:

     ?  :   -->  
    

    It takes 3 evaluable parts, and returns a value.

    The first evaluable part must be understandable (castable) by the compiler as a boolean. It will be used to decide which of the other 2 evaluable parts has to be returned.

    The other two evaluable parts must be, well... evaluable. To something. Of some type.

    In other words: the ternary conditional operator is intended to return something, not as code branching. Used this way:

    gimmeAValue = testMe() ? returnThis() : returnThat();
    

提交回复
热议问题