Expression switch - an alternate proposal
Brian Goetz
brian.goetz at oracle.com
Thu Apr 12 23:59:52 UTC 2018
> Perhaps you shouldn't allow statements in a switch expression? They aren't allowed in a ? : expression either.
Are you kidding? We’d get lynched. If you want to put one logging statement in one case of a 50 case switch, or construct a list and add to it, or have to call a setter on the thing you’re returning, or do something in a loop to build the result, you have to refactor the whole thing to a statement switch? We’d get laughed out of the room.
Statements are a pain; no doubt. But we can’t hide our heads in the sand and pretend they don’t exist. We have to engage them as consistently and constructively as we can.
> 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.
> Is there a restriction on what can go into the semicolon-separated list of statements in the case label of an expression switch? I couldn't see one in the JEP. And if not, what happens if there is a return? A break without value? A continue?
Return, continue, break without value, and break with label are forbidden (not unlike lambdas.) Of course, you can have a statement switch inside of it, and you can break out of that — but not _through_ an expression switch (not unlike lambdas.)
> 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.
More information about the amber-dev
mailing list