Switch case scoping change
Stephen Colebourne
scolebourne at joda.org
Tue Apr 10 21:36:04 UTC 2018
One of my objections to switch is that each case clause is not its own
scope. I've argued previously that expression switch should enforce
curly braces to tackle that problem. But having thought about it
today, I don't think forcing curly braces is necessary.
This code does not compile because variable x cannot be declared twice:
switch (light) {
case RED:
int x = calculateRed();
break;
case GREEN:
int x = calculateGreen();
break;
}
It seems to me that this could be made to compile, by adding a scope
boundary for each CASE clause without creating backwards compatibility
issues. This could be done for both statement and expression switches,
and may be needed anyway given that pattern matching will create more
local variables.
(JLS 6.3 already carves out a scope boundary for
`SwitchBlockStatementGroup` wrt local classes, so this is not
unprecedented)
Unfortunately there is a small problem that needs an extra rule:
switch (light) {
case YELLOW:
int x = calculateYellow();
// fallthrough
case GREEN:
x = calculateGreen();
break;
}
Case GREEN can assign to the local variable that was setup in case
YELLOW. It can't read from it until it is DA.
I think this requires one additional rule: If a local variable in one
case is used by a subsequent case via fall through, the local variable
is redefined in the scope of the second case. ie the code above would
be semantically equivalent to:
switch (light) {
case YELLOW: {
int x = calculateYellow();
// fallthrough
}
case GREEN: {
int x; // added to meet the additional rule
x = calculateGreen();
break;
}
}
Have I've missed any other backwards compatibility issues?
While I know that no-one loves the lack of curly braces as the scope
boundary, I don't think it would be surprising for anyone who has used
Java. (Maybe not ideal for those fresh to Java, but switch is already
far from ideal).
If we are going to have BlockStatements after a colon in expression
switch rather than a block expression, this feels like a change I need
to make it palatable.
Stephen
More information about the amber-dev
mailing list