What type of token exactly is “var” in Java 10?

前端 未结 2 787
春和景丽
春和景丽 2020-12-09 16:27

In the last issue of Heinz Kabutz\'s newsletter, #255 Java 10: Inferred Local Variables, it is shown that var is not a reserved word in Java 10, because you can

相关标签:
2条回答
  • 2020-12-09 17:24

    var is a reserved type name var is not a keyword, It’s a reserved type name.

    We can create a variable named “var”.

    you can read here for more details.

    var var = 5; // syntactically correct
    // var is the name of the variable
    “var” as a method name is allowed.
    
    public static void var() { // syntactically correct 
    }
    “var” as a package name is allowed.
    
    package var; // syntactically correct
    “var” cannot be used as the name of a class or interface.
    class var{ } // Compile Error
    LocalTypeInference.java:45: error: 'var' not allowed here
    class var{
          ^
      as of release 10, 'var' is a restricted local variable type and cannot be used for type declarations
    1 error
    
    interface var{ } // Compile Error
    
    var author = null; // Null cannot be inferred to a type 
    LocalTypeInference.java:47: error: cannot infer type for local variable author
                    var author = null;
                        ^
      (variable initializer is 'null')
    1 error
    
    0 讨论(0)
  • 2020-12-09 17:27

    According to JEP-286: Local-Variable Type Inference, var is

    not a keyword; instead it is a reserved type name.

    (Earlier versions of the JEP left room for implementing either as a reserved type name or as a context-sensitive keyword; the former path was ultimately chosen.)

    Because it's not a "reserved keyword", it is possible to still use it in variable names (and package names), but not in class or interface names.

    I would think the biggest reason for not making var a reserved keyword is backwards compatibility with old source code.

    0 讨论(0)
提交回复
热议问题