Details

    • Type: Sub-task
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 5.3
    • Component/s: Semantic
    • Labels:
      None

      Description

      The type of a variable declared using Java 10 var is the upward projection from its initializer type (see JLS10 - §4.10.5).

      The type of a local variable is determined as follow:

      • If LocalVariableType is var, then let T be the type of the initializer expression when treated as if it did not appear in an assignment context, and were thus a standalone expression (§15.2). The type of the local variable is the upward projection of T with respect to all synthetic type variables mentioned by T (§4.10.5).

      With the following constraints:

      • It is a compile-time error if T is the null type.
      • Because the initializer is treated as if it did not appear in an assignment context, an error occurs if it is a lambda expression (§15.27) or a method reference expression (§15.13).

      Note that for variable declared using var, an initializer is required!

      var a = 1;            // Legal
      var b = 2, c = 3.0;   // Illegal: multiple declarators
      var d[] = new int[4]; // Illegal: extra bracket pairs
      var e;                // Illegal: no initializer
      var f = { 6 };        // Illegal: array initializer
      var g = (g = 7);      // Illegal: self reference in initializer
      

      More details are expressed regarding type resolution in JLS10 - §14.4.1. Local Variable Declarators and Types.

      Another case, to be confirmed, documented and verified: We should be able to access fields from anonymous classes declared with a var, outside of the body of the anonymous class.

      var myA = new A() { 
      
        Object myField;
      
        @Override
        void foo() {
          // do Something...
          this.myField = verifySomething(someParameters);
        }
      };
      
      // ...
      
      myA.foo();
      
      // ...
      
      if (myA.myField != null) { // <<<<<<< myField is visible and resolved
        // ...
      }
      

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                michael.gumowski Michael Gumowski
                Reporter:
                michael.gumowski Michael Gumowski
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Due:
                  Created:
                  Updated:
                  Resolved: