问题
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