[External] : Re: Switch coverage with multiple branches
Dan Smith
daniel.smith at oracle.com
Sun Jul 25 17:02:09 UTC 2021
> On Jul 23, 2021, at 3:48 PM, Remi Forax <forax at univ-mlv.fr> wrote:
>
> ----- 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.
>
> Should it compile if C is declared as non-sealed ?
No. The analysis would see that
C = { D1, D2 }
and then note that
{ D1, D2 } is covered by { B1, B2 }
More information about the amber-spec-observers
mailing list