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

Compiler should accept var _ in nested patterns in switch case

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Fixed
    • Icon: P4 P4
    • 21
    • None
    • tools
    • None
    • b24

      The spec (https://cr.openjdk.org/~abimpoudis/unnamed/jep443-20230322/specs/unnamed-jls.html) says:

      SwitchLabel:
      case CaseConstant {, CaseConstant}
      case null [, default]
      case CasePattern{, CasePattern } [ Guard ]
      default
      CaseConstant:
      ConditionalExpression
      CasePattern:
      Pattern
      ….
       
      Pattern:
      TypePattern
      RecordPattern
      TypePattern:
      LocalVariableDeclaration
      The following productions from 4.3, 8.3, 8.4.1, and 14.4 are shown here for convenience:
      LocalVariableDeclaration:
      {VariableModifier} LocalVariableType VariableDeclaratorList
      VariableModifier:
      Annotation
      final
      LocalVariableType:
      UnannType
      var
       
      And JDK-8307444 says:
      Neither the unnamed pattern nor var _ may be used at the top level of a pattern, so all of these are prohibited:

          ... instanceof _
          ... instanceof var _
          case _
          case var _

      So, using var _ in nested patterns should be accepted by the compiler.

      But this code fails:

      record TestRecord<T>(T a) {}
          private static <T> int consume(T t) {
              return switch(t) {
                  case TestRecord(var _), TestRecord(Integer _) : { //java: as of release 9, '_' is a keyword, and may not be used as an identifier
                      yield 1;
                  }
                  default : {
                      yield -2;
                  }
              };
          }

          public static void main(String argv[]) {
              System.out.println(consume(new TestRecord("test")));
          }

      java --version
      java 21-internal 2023-09-19 LTS
      Java(TM) SE Runtime Environment (build 21-internal-LTS-2023-04-30-1558228.angelos.bimpoudis.dev)
      Java HotSpot(TM) 64-Bit Server VM (build 21-internal-LTS-2023-04-30-1558228.angelos.bimpoudis.dev, mixed mode, sharing)

            abimpoudis Angelos Bimpoudis
            eananeva Ella Ananeva
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: