[patterns] Multiple patterns without unnamed variables

Tagir Valeev amaembo at gmail.com
Wed Aug 16 09:07:16 UTC 2023


Just discovered a small discrepancy between spec and implementation in
JDK 21. Consider the following code:

public class Test {
  record R1() {}
  record R2() {}

  static void test(Object obj) {
    switch (obj) {
      case R1(), R2() -> System.out.println("R1 or R2");
      default -> System.out.println("other");

  public static void main(String[] args) {
    test(new R1());

It can be executed using java build 21-ea+27-2343 _without_ enabling preview:

>\jdks\jdk-21\bin\java.exe Test.java
R1 or R2

However, the spec draft for JDK 21 [1] doesn't allow several patterns
in the same switch label. See the SwitchLabel production on the page 501:

  case CaseConstant {, CaseConstant}
  case null [, default]
  case CasePattern [Guard] // only one pattern is allowed!

Such code is legal under JEP-443 but it should require
--enable-preview. On the other hand, I understand how it happens.
Probably it would be better to update the JDK 21 spec to allow it? Or
it should be considered as a compiler bug?

With best regards,
Tagir Valeev.

[1] https://cr.openjdk.org/~iris/se/21/latestSpec/java-se-21-jls-pr-diffs.pdf

More information about the amber-spec-experts mailing list