Next up for patterns: type patterns in switch
Brian Goetz
brian.goetz at oracle.com
Tue Aug 11 22:51:59 UTC 2020
> If it is, the last clause is total too (well, unless it is an enum
> switch that names all the constants, or a switch over a sealed type
> that names all the sub-types but without a catch-all.)
I want to drill into this comment because it's significant.
If we have
enum E { A, B; }
then a switch
switch (e) {
case A: ...
case B: ....
}
is exhaustive but has no catch-all and will still NPE on null. (Which
seems reasonable, there's a strong presumption that null enum values are
a bug.) And we would not want to make the user explicitly say `case
null`, just like we don't make them say `default` when all the cases are
covered.
Presumably the same is true with:
sealed interface E permits A, B { }
switch (e) {
case A a:
case B b:
}
and presumably this is also reasonable.
Which is to say: the nullity behaviors we've designed around pattern
matching are specific to catch-all cases, which we presume are going to
be common in pattern switches. If null is not part of your domain, you
won't notice; if it is part of your domain, you want the catch-all
catching it.
More information about the amber-spec-experts
mailing list