Question about pattern matching and sealed types – redundant switch cases

Andreas Berheim Brudin andreas.brudin at gmail.com
Sat Apr 19 16:17:43 UTC 2025


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/9149b07e/attachment-0001.htm>


More information about the amber-dev mailing list