Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrictions on using Local-Variable Type Inference in java 10

Tags:

java

java-10

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 ?

like image 261
Niraj Sonawane Avatar asked Mar 10 '18 15:03

Niraj Sonawane


1 Answers

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)
like image 87
Niraj Sonawane Avatar answered Oct 28 '22 22:10

Niraj Sonawane