Expression switch - an alternate proposal
Cay Horstmann
cay.horstmann at sjsu.edu
Fri Apr 13 04:42:13 UTC 2018
>> I also don't understand Rémy's remark that a traditional break inside a switch expression is disallowed. What rules out
>>
>> case BAKED_POTATO:
>> Toppings t = new Toppings();
>> t.add(SOUR_CREAM);
>> t.add(CHEESE);
>> int count = 0;
>> while (true) {
>> if (count == 10) break; else count++;
>> t.add(BACON);
>> }
>> break t;
>
> You can’t say “break” without a value in an expression switch, just like you can’t say “return” without a value in a value-bearing method.
The break in "if (count == 10) break; ..." is nested inside a while
which is nested inside a case inside an expression switch. That's
perfectly legal. My second example, where "break t" is contained inside
the "while (true)" is not helpful to the cause of clarity.
Puzzler authors will mercilessly probe break vs. break label vs. break
value in this context. It won't be pretty.
>> It seems that, if variable declarations are allowed in an expression switch, the rules are going to have to be different :-)
>
> The rules are the same. Same old switch. That’s the point.
That is not going to be pleasant either. The rules for variable
declarations in statement switch are a consequence of the possibility of
fall through from one branch to another. In expression switch, the
branches have no fall through. Why shouldn't you be able to define the
same variable in two branches of expression switch? And, again in
expression switch, surely you can't read the same variable in a branch
and in the default branch, as you can in statement switch.
I am all for an expression switch/match/whatever, but the more I try to
wrap my head around it, the less I am convinced that statement switch is
the best point of departure for it.
Cheers,
Cay
--
Cay S. Horstmann | http://horstmann.com | mailto:cay at horstmann.com
More information about the amber-dev
mailing list