3

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
  • 21,685
  • 24
  • 196
  • 332

2 Answers2

7

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
  • 21,685
  • 24
  • 196
  • 332
Jacob G.
  • 27,643
  • 5
  • 54
  • 108
4

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,084
  • 3
  • 19
  • 45