Re: Question about pattern matching and sealed types – redundant switch cases

Remi Forax forax at univ-mlv.fr
Sat Apr 19 17:17:18 UTC 2025


> From: "Brian Goetz" <brian.goetz at oracle.com>
> To: "Andreas Berheim Brudin" <andreas.brudin at gmail.com>, "amber-dev"
> <amber-dev at openjdk.org>
> Sent: Saturday, April 19, 2025 6:59:57 PM
> Subject: Re: Question about pattern matching and sealed types – redundant switch
> cases

> This doesn't really have as much to do with sealed types or pattern matching as
> it might seem; it has to do with to what degree the language is willing to
> engage in flow-based type analysis.

> The short answer is: there's not a lot of appetite for investing in this. The
> cost and complexity is likely high both initially and ongoing, and the impact
> on program correctness is fairly marginal. (The simple cases are easy, but just
> handling the simple cases is a recipe for an infinite stream of enhancement
> requests.)

> If we're going to invest at all in flow-based type analysis, we'd likely start
> with nullity analysis. This is a simpler problem (and still, not simple) and
> probably would have more impact.
This is also because we may restrict nullity analysis to only a type-checking pass that has no impact on the generated code while general flow typing change the generated code by changing method selection, inserting casts or instanceof + throw so adding such analysis after the fact is more disruptive. 

regards, 
Rémi 

> On 4/19/2025 12:17 PM, Andreas Berheim Brudin wrote:

>> Hi all,

>> I'm new to the list—apologies if this has been discussed before, and thanks in
>> advance for your time.

>> I have a question about pattern matching with sealed types. Consider this
>> example:

>> sealed interface A permits B, C {}
>> record B(String b1, String b2) implements A {}
>> record C(String c) implements A {}

>> A myVar = ...;
>> if (!(myVar instanceof B(var b1, var b2))) {
>> return switch (myVar) {
>> case C(var c) -> c;
>> case B b -> throw new IllegalStateException("should not happen");
>> };
>> }
>> // use b1, b2

>> Here, I want to keep an early-return style, but since I need to return a value
>> from C, I have to use a switch. This leads to redundancy: we've already tested
>> myVar is not a B, so that case should be statically unreachable.

>> My questions:

>> 1. Is there any consideration or ongoing work to allow the compiler to
>> automatically eliminate such unreachable cases?

>> 2. If only one case remains (in this case, C), could it be possible to treat the
>> variable as a C directly without requiring an explicit switch?

>> Again, apologies if this has already been discussed. I'd appreciate any pointers
>> to relevant threads or JEPs if so.

>> Thanks,
>> Andreas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20250419/3b4263bd/attachment.htm>


More information about the amber-dev mailing list