0
class ExampleClass {
    var a = 0; // Not Allowed
    static var b = 0; // Not Allowed 

    void exampleMethod() {
        var c = 3; // Allowed
    }
}

In the above example, both a and b can have their type determined at compile time. Yet, var is allowed only for local variables whose type can inferred. Is there a design reason I'm missing as to why this is the case?

I've looked at this question which explains the use and intent behind var, but its answer does not acknowledge reasons for the the above limitation.

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
  • 2
    Refer to [First Contact With ‘var’ In Java 10](https://blog.codefx.org/java/java-10-var-type-inference/), the `Why Can’t Field And Method Types Be Inferred?` part. – Lebecca Dec 13 '19 at 01:48

1 Answers1

0

One way to put it is that it simply wasn't designed for it.

Although 'var' has been introduced in Java 10, it comes with its limitations.

The documentation clearly states when 'var' can be used, namely only during these conditions:

  • Local variable declaration with Initialisers(i.e., methods and initializer blocks).
  • Indexes in enhanced for loops.
  • Index variables in traditional for loops.
  • Try-with-resources variable.

Read Documentation here