Use var in field declaration

五迷三道 提交于 2020-01-02 10:00:32

问题


So starting in Java 9, we can use var to declare local variables:

var s = "cool";

is there a way to use a similar construct when declaring fields?

class Container {
  final var s = "cool"; // does not compile tmk
}

doesn't seem like it from what I can tell.


回答1:


is there a way to use a similar construct when declaring fields?

No.

According to JEP 286: Local-Variable Type Inference:

This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals or any other kind of variable declaration.




回答2:


No, there is not.

var is not a keyword, but rather an identifier with special meaning as the type of a local variable declaration (§14.4, §14.14.1, §14.14.2, §14.20.3).

var can only be used in local variable declaration statements with the syntax

LocalVariableDeclarationStatement:
    LocalVariableDeclaration ;
LocalVariableDeclaration:
    {VariableModifier} LocalVariableType VariableDeclaratorList
LocalVariableType:
    UnannType 
    var

Field declarations do not contain syntax where the var special identifier is allowed:

FieldDeclaration:
    {FieldModifier} UnannType VariableDeclaratorList ;


来源:https://stackoverflow.com/questions/54662190/use-var-in-field-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!