8

Java 10 has introduce Local-Variable Type Inference feature JEP-286.

We can use Local-Variable Type Inference using var which is reserved type name

But there are some restrictions of using it.

Can someone please summarise in which cases i will be not able to use var ?

Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104
  • 2
    Too broad? Interesting reads https://stackoverflow.com/questions/49154458/why-are-compound-definitions-using-var-not-allowed; https://stackoverflow.com/questions/49134118/array-initializer-needs-an-explicit-target-type-why; – Naman Mar 10 '18 at 18:24
  • the intentions is not to get into why it's not allowed , rather than just to note down whats not allowed. not sure if it is too broad and deserved to be close – Niraj Sonawane Mar 12 '18 at 05:56
  • 1
    IT's very well explained in the link you shared under `Risks and Assumptions` section – Vinay Prajapati Mar 22 '18 at 20:55

1 Answers1

8

1. As the name suggests, you can use it only for local variables.

2. Local type inference cannot be used for variables with no initializers

e.g Below code will not work

Case 1:

  var xyz = null;
            ^
  (variable initializer is 'null')

Case 2:

var xyz;
            ^
  (cannot use 'val' on variable without initializer)

Case 3:

   var xyz = () -> { };
            ^
  (lambda expression needs an explicit target-type) 

3. Var can not used to instantiate multiple variables on same line

More details can be found here Suggested by nullpointer

   var X=10,Y=20,Z=30 // this is not allowed 

4: Var as Parameters

   3.1 var would not be available for method parameters.

   3.2 Var would not be available for constructor parameters.

   3.3 Var would not be available for method return types.

   3.4 Var would not be available for catch parameters.

4. Array initializer is not allowed More details can by found here Suggested by Nicolai

var k = { 1 , 2 };
        ^   
(array initializer needs an explicit target-type)

5. Method reference is not allowed

var someVal = this::getName;  
 error: cannot infer type for local variable nameFetcher
  (method reference needs an explicit target-type)
Niraj Sonawane
  • 10,225
  • 10
  • 75
  • 104