Restrictions on using Local-Variable Type Inference in java 10

人走茶凉 提交于 2019-12-21 05:02:32

问题


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)


来源:https://stackoverflow.com/questions/49210591/restrictions-on-using-local-variable-type-inference-in-java-10

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!