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?
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 asa?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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With