Switch coverage with multiple branches
Dan Smith
daniel.smith at oracle.com
Fri Jul 23 22:28:08 UTC 2021
An RFE for JEP 406 (or maybe bug fix? I haven't dug into what the spec says). Can we make this compile?
public class SwitchCoverage {
sealed interface A {}
sealed interface B1 extends A {}
sealed interface B2 extends A {}
sealed interface C extends A {}
final class D1 implements B1, C {}
final class D2 implements B2, C {}
void test(A arg) {
int i = switch (arg) {
case B1 b1 -> 1;
case B2 b2 -> 2;
};
}
}
Output:
% -> `javahome 17`/bin/javac --enable-preview --release 17 SwitchCoverage.java
SwitchCoverage.java:10: error: the switch expression does not cover all possible input values
int i = switch (arg) {
^
Note: SwitchCoverage.java uses preview features of Java SE 17.
Note: Recompile with -Xlint:preview for details.
1 error
The compiler wants to see a 'case C c', not realizing that the combination of B1 and B2 already covers C.
The use case might seem a impractically complex, but I think it's actually pretty normal to want to define a universe of values (that's A), provide some implementations (D1 and D2), and then categorize the implementations in different dimensions (B1/B2 in one dimension, C in another). When I'm writing my switch, I might only care about one of these dimensions.
More information about the amber-spec-experts
mailing list