[patterns-switch] Draft JLS spec for JEP 406 (Pattern Matching for Switch)
Gavin Bierman
gavin.bierman at oracle.com
Fri Apr 23 15:58:38 UTC 2021
Dear experts,
Apologies for the delay, but here is the first draft of the spec for JEP 406 (Pattern Matching for Switch):
http://cr.openjdk.java.net/~gbierman/jep406/latest/
As you will see, the design has evolved a little since we wrote the JEP (which I will update shortly). The chief changes are:
1. Instead of enumerating the special case labels, e.g. case null, default, case null, T t and so on; the notion of switch label has been made more general, with a set of restrictions to cut out the things we don’t want. In particular, this means that we get (a) symmetric versions of the compound patterns, e.g. case null, default and case default, null: and (b) we get a perfect alignment of the old : style with the new , style, e.g. we can write both `case null, default: …` and `case null: default: …` with identical treatment.
2. I figured out a way to remove the restriction from the JEP that switches must be all pattern-matching, or all non-pattern-matching. Apart from simplifying matters, this allows for some nice new features, e.g.
enum E { F, G, H }
switch(...) { // A switch block with an enum constant and pattern label!
case F -> …
case E e -> … // Acts like a default but e is in scope!
}
A couple of odd extras come for the ride, just for your information:
switch(o) { /* empty */ }
is now well-typed for all types of o, as is:
switch(o) { default: … }
[Basically any type restrictions on the selector expression come from the switch labels. We still maintain that if you use a constant case label, the type of the selector must be char, byte, short, int, Character, Byte, Short, Integer, or String as in Java 16.]
As always, your opinions are welcomed!
Thanks,
Gavin
More information about the amber-spec-experts
mailing list