在 java 10 中使用局部变量类型推断的限制

Restrictions on using Local-Variable Type Inference in java 10

Java 10 引入了局部变量类型推断 特性JEP-286

我们可以使用 var 的局部变量类型推断,它是 保留类型名称

但是在使用上有一些限制。

有人可以总结一下在哪些情况下我将无法使用 var 吗?

1.顾名思义,只能用于局部变量。

2.局部类型推断不能用于没有初始值设定项的变量

例如下面的代码将不起作用

案例一:

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

案例二:

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

案例三:

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

3. Var不能在同一行实例化多个变量

可以找到更多详细信息 由 nullpointer 建议

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

4: Var 作为参数

   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.不允许数组初始值设定项 可以找到更多详细信息 由 Nicolai 建议

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

5.不允许引用方法

var someVal = this::getName;  
 error: cannot infer type for local variable nameFetcher
  (method reference needs an explicit target-type)