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

Compiler should accept final unnamed variables in try-with-resources

XMLWordPrintable

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

      Spec (https://cr.openjdk.org/~abimpoudis/unnamed/jep443-20230322/specs/unnamed-jls.html#jls-14.20.3) says:
      Alternatively, the meaning of a basic try-with-resources statement of the form:

      try ({VariableModifier} R _ = Expression ...)
          Block

      is given by the following translation to a local variable declaration and a try-catch-finally statement:

      {
          final {VariableModifierNoFinal} R #i = Expression;
          Throwable #primaryExc = null;

          try ResourceSpecification_tail
              Block
          catch (Throwable #t) {
              #primaryExc = #t;
              throw #t;
          } finally {
              if (#i != null) {
                  if (#primaryExc != null) {
                      try {
                          #i.close();
                      } catch (Throwable #suppressedExc) {
                          #primaryExc.addSuppressed(#suppressedExc);
                      }
                  } else {
                      #i.close();
                  }
              }
          }
      }

      {VariableModifierNoFinal} is defined as {VariableModifier} without final, if present. [jck-14.20.3.1-220-upv]
      #t, #primaryExc, #suppressedExc, and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the try-with-resources statement occurs. [jck-14.20.3.1-230-upv]



      class Door implements AutoCloseable {
          public void close() { }
      }

      public class Example {

          public static void main(String argv[]) {
              try ( final Door _ = new Door();) { //compile-time error: java: as of release 21, the underscore keyword '_' is only allowed to declare
        unnamed patterns, local variables, exception parameters or lambda parameters
              }
          }


      java --version
      java 21-ea 2023-09-19 LTS
      Java(TM) SE Runtime Environment (build 21-ea+24-LTS-2081)
      Java HotSpot(TM) 64-Bit Server VM (build 21-ea+24-LTS-2081, mixed mode, sharing)

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

              Created:
              Updated:
              Resolved: