Use var in field declaration

試著忘記壹切 提交于 2019-12-06 08:38:29
Jacob G.

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.

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