Java Ternary Operator inside ternary operator, how

2019-05-08 19:41发布

问题:

Very basic question I suppose, I just wanted to know how this code is read:

return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance(); 

I guess now as I'm writing it I kind of understand the statement. It returns option one if true but then does another boolean check if false and returns one of the two remaining options? I'm going to continue to leave this question because I have not seen it before and maybe others have not as well.

Could you go on indefinitely with ternary inside of ternary operations?

Edit: Also why is this/is this not better for code than using a bunch of if statements?

回答1:

It is defined in JLS #15.25:

The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

In your case,

return someboolean ? new someinstanceofsomething() : someotherboolean ? new otherinstance() : new third instance();

is equivalent to:

return someboolean ? new someinstanceofsomething() : (someotherboolean ? new otherinstance() : new third instance());


回答2:

Ternary operators are right-associative. See assylias's answer for the JLS reference.

Your example would translate to:

if (someboolean) {
  return new someinstanceofsomething();
} else {
  if (someotherboolean) {
    return new otherinstance();
  } else {
    return new thirdinstance()
  }
}

And yes, you can nest these indefinitely.