[deconstruction-patterns] Unconditional patterns and null (again)

Tagir Valeev amaembo at gmail.com
Tue Oct 25 09:59:18 UTC 2022


I've just discovered that recent builds of JDK 19 and JDK 20 accept
this code, which fails with NPE at runtime:

class Test {
    record R(int x) {}

    static void test(R r) {
        switch (r) {
            case R(int x) -> System.out.println("matched");
            default -> System.out.println("not matched");

    public static void main(String[] args) {

If I remember correctly, it was rejected previously with error similar
to this (you can emulate the error replacing `R(int x)` with `R r1`
> Test.java:7: error: switch has both an unconditional pattern and a default label

I see that in a recent spec draft [1] it's said that:
> Note that record patterns are not unconditional at any type because the null reference does not match any record pattern.

Which makes sense. And it looks like that compiler follows the spec.
However, we all know that the default branch is not reachable in this
switch, so we effectively accept unreachable code. Is this intended or
should be changed somehow?

With best regards,
Tagir Valeev

[1] https://docs.oracle.com/javase/specs/jls/se19/preview/specs/patterns-switch-record-patterns-jls.html#jls-14.30.3

More information about the amber-spec-experts mailing list