JEP 441: Pattern Matching for switch (suggestion re: handling sealed type selector expressions)
Robert
roberts14 at cablelink.at
Sat Apr 8 17:09:18 UTC 2023
Hi all, newbie here.
First off — loving Amber features.
Now, a *very narrow* observation about how JDK 20 handles sealed type selector expressions.
(Code snippet below.)
If a sealed type S later grows its list of permitted subtypes at some point,
how should the compiler handle switch blocks with S as selector?
In the absence of a catchall label (i.e. “case default -> ...” or “case S s -> ...”) ,
the compiler already correctly issues an error that coverage is incomplete.
But if the block ended with a catchall label, the compiler is silent; the best that
can be hoped-for is that the coder throws a defensive exception in the catchall label
(and hope that it is triggered in testing).
Suggestion:
Compiler should *disallows* catchall statements in switch blocks that use a sealed type
in the switch selector expression. Note that this special case does not affect all the
other non-sealed-type selectors (e.g. Object o), and appears (to me) to strengthen the
safety-value of sealed types in this particular scenario (similar to enums).
All in Java’s spirit of “least surprise”.
Cheers,
Robert
PS. reported behavior confirmed using jshell in JDK 20:
jshell --enable-preview
| Welcome to JShell -- Version 20
| For an introduction type: /help intro
on the following:
sealed interface S permits S.X, S.Y, S.Z, S.NEWBIE {
final class X implements S {};
final class Y implements S {};
final class Z implements S {};
final class NEWBIE implements S {};
public static void main(String [] sa) {
S something = new NEWBIE();
System.out.println(
switch (something) {
case null -> 0;
case X x -> 1;
case Y y -> 2;
case Z z -> 3;
case S s -> -1;
// case default -> -1;
});
};
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20230408/c0bfa9bb/attachment.htm>
More information about the amber-dev
mailing list