Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...