Switch coverage with multiple branches
Remi Forax
forax at univ-mlv.fr
Thu Aug 26 19:06:24 UTC 2021
Here is another example with i believe the same issue
sealed interface Vehicle {}
record Car(String owner, String color) implements Vehicle {}
record Bus(String owner) implements Vehicle {}
public static void example2() {
var vehicles = List.<Vehicle>of(
new Car("Bob", "red"),
new Bus("Ana")
);
for(var vehicle: vehicles) {
switch(vehicle) {
case Car car -> System.out.println("car !");
case Bus bus -> System.out.println("bus !");
case Record record -> throw new AssertionError();
}
}
}
This code currently compiles even if the last case is not reachable.
Rémi
----- Original Message -----
> From: "daniel smith" <daniel.smith at oracle.com>
> To: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Cc: "Gavin Bierman" <gavin.bierman at oracle.com>
> Sent: Samedi 24 Juillet 2021 00:28:08
> Subject: Switch coverage with multiple branches
> 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