Java Single Conditional Operator
Brian Goetz
brian.goetz at oracle.com
Tue Aug 23 20:31:53 UTC 2022
Let’s go back to why we have the ternary expression in the first place. Contrary to popular belief, it is *not* for syntactic concision.
The difference between
int x;
If (b)
x = a;
else
x = b;
and
Int x = b ? a : b
Is that the latter is a _more constrained_ construct than the former. In the former, the then/else blocks of the if can contain arbitrary statements, and there is no way (other than DA/DU analysis) to capture the intention that we will assign to x in each arm (or even that there are both arms.) Whereas the latter is an _expression_, and expressions are _total_. So the latter makes use of a more constrained mechanism, and therefore allows for richer type-checking. The concision is merely a bonus.
Your proposal conflates statements and expressions; the ternary conditional is an expression, whose arms are expressions, but you want to use a version of it for statements. And why? So you can type *two fewer characters*. It offers no additional type checking, introduces a gratuitously different way to do the same thing, and creates the Frankenstein monster of an operator that is really a statement. And it doesn’t result in more readable code; arguably, less readable, since we’re less use to spotting side-effects nestled in what look like expressions.
If you mean “if (condition) do stuff”, then there’s no shame in saying exactly that.
On Aug 23, 2022, at 2:28 PM, sankar singh <sankar.singu at gmail.com<mailto:sankar.singu at gmail.com>> wrote:
Hi Team,
We are using ternary operator
Can we use single conditional code like the below.
if (a>50)
print("50 more")
a>50?. print("50 more")
--
regards,
Shankar.S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220823/c6cc9254/attachment.htm>
More information about the amber-dev
mailing list