Restrictions on using Local-Variable Type Inferenc

2019-03-29 04:18发布

问题:

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 ?

回答1:

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)


标签: java java-10