Treatment of nested 'break'

Dan Smith daniel.smith at
Tue May 8 22:37:09 UTC 2018

I am concerned about the treatment of 'break' statements in switch expressions. The following seems like something that would be very natural to do:

boolean x = switch (expr()) {
    case FOO -> {
        for (String s : strings) {
            if (s.isEmpty()) break false;
        break true;
    case BAR -> true;
    default -> false;

This is specified as a compiler error, even though the intent is clear, and we allow code of this shape in other contexts (compare, e.g., a method body).

I think what prompted this degree of brittleness is worries about ambiguity between label breaks and value breaks. Let me suggest this disambiguation strategy instead (in the spirit of 6.5.2):
- If an unqualified name appears immediately after a 'break' and occurs in the scope of a label with that name, it is a LabelName
- Otherwise, it is an ExpressionName

(In practice, I expect it to be rare for a real ambiguity to exist between a label name and a variable name.)

With that disambiguation rule in place, we can then treat value breaks much like label breaks:

"If no switch expression in the immediately enclosing method, constructor, initializer, or lambda body contains the break statement, a compile-time error occurs."

(No special rule about appearing inside a 'while', 'for', etc.)

More information about the amber-spec-experts mailing list