Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8352621

MatchException from backwards incompatible change to switch expressions

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P2 P2
    • 25
    • None
    • tools
    • None
    • Cause Known

      The following example fails with an unexpected MatchException when compiled with JDK 25 and executed on JDK 21.

      The change bisects to between jdk-23+7 and jdk-23+8, I think the culprit may be JDK-8303374 (Implement JEP 455: Primitive Types in Patterns, instanceof, and switch)

      class B {

        sealed interface Foo {}
        record StringRecord(String s, boolean b) implements Foo {}
        record LongRecord(long a, boolean b) implements Foo {}

        static String string4(Foo foo) {
          return switch (foo) {
            case StringRecord(String s, boolean b) when b -> s;
            case StringRecord(String s, boolean b) -> s;
            case LongRecord(long a, boolean b) when b -> Long.toString(a);
            case LongRecord(long a, boolean b) -> Long.toString(a);
          };
        }

        public static void main(String[] args) {
          System.out.println(string4(new LongRecord(42, true)));
        }
      }

      $JDK21/bin/javac --release 21 B.java && $JDK21/bin/java B
      42

      $JDK25/bin/javac --release 21 B.java && $JDK21/bin/java B
      Exception in thread "main" java.lang.MatchException
              at B.string4(B.java:8)
              at B.main(B.java:17)

      $JDK25/bin/javac --release 21 B.java && $JDK25/bin/java B
      42

            jlahoda Jan Lahoda
            cushon Liam Miller-Cushon
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: