[patterns] Domination in guarded multiple pattern labels
Tagir Valeev
amaembo at gmail.com
Fri Aug 18 09:48:09 UTC 2023
Hello!
Consider the following code:
public class Test {
void test(Object obj) {
switch (obj) {
case Integer _, CharSequence _, String _ when obj.hashCode() > 0 -> {
}
default -> throw new IllegalStateException("Unexpected
value: " + obj);
}
}
}
Javac compiles it, despite the `String _` pattern being unreachable.
It looks like the spec [1] allows it. It speaks about domination of
case labels, but not about the domination of individual patterns
within the case label. I think this part should be improved. Namely,
for several patterns under the single case label, domination rules
must apply, and the guard must be ignored.
It's interesting that if we remove the guard, the compilation fails:
Test.java:4:45
java: this case label is dominated by a preceding case label
While formally according to the spec, this should be accepted, as spec
in its current shape says us only about 'preceding case label', and
there's no preceding case label at all, so the first label should not
be dominated.
With best regards,
Tagir Valeev
[1] https://cr.openjdk.org/~abimpoudis/unnamed/jep443-20230322/specs/unnamed-jls.html#jls-14.11.1
More information about the amber-spec-experts
mailing list