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 calling, like this:
(condition) ? doThis() : doThat();
Both methods return void. Java tells me it is not a statement.
So, I'm guessing I can't do conditional method calling... or can I?
解决方案
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.