5

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.

Naman
  • 27,789
  • 26
  • 218
  • 353

2 Answers2

8

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
5

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 ;
Savior
  • 3,225
  • 4
  • 24
  • 48