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

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

    Think of ternary operators like a method in this case. Saying a ? b : c is (for the intents and purposes you're considering, see lasseespeholt's comment) equivalent to calling the pseudocode method:

    ternary(a, b, c)
        if a
            return b
        else
            return c
    

    which is why people can say things like x = a ? b : c; it's basically like saying x = ternary(a, b, c). When you say (condition) ? doThis() : doThat(), you're in effect saying:

    if condition
        return doThis()
    else
        return doThat()
    

    Look what happens if we try to substitute the methods for what they return

     if condition
        return ???
     else
        return ???
    

    It doesn't even make sense to consider it. doThis() and doThat() don't return anything, because void isn't an instantiable type, so the ternary method can't return anything either, so Java doesn't know what to do with your statement and complains.

    There are ways around this, but they're all bad practice (you could modify your methods to have a return value but don't do anything with what they return, you could create new methods that call your methods and then return null, etc.). You're much better off just using an if statement in this case.

    EDIT Furthermore, there's an even bigger issue. Even if you were returning values, Java does not consider a ? b : c a statement in any sense.

提交回复
热议问题