Java Ternary Operator inside ternary operator, how

2019-05-08 19:07发布

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-05-08 19:45

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.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-05-08 20:00

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());
查看更多
登录 后发表回答