Java 10介绍了局部变量类型推断特性二八六.
我们可以使用保留类型名称的var进行局部变量类型推断
但是使用它有一些限制。
有人能总结一下在哪些情况下我不能使用var吗?
发布于 2018-03-10 15:10:37
1.顾名思义,只能用于局部变量.
2.没有初始化项的变量不能使用局部类型推断
下面的代码不起作用
案例1:
var xyz = null;
^
(variable initializer is 'null')案例2:
var xyz;
^
(cannot use 'val' on variable without initializer)案例3:
var xyz = () -> { };
^
(lambda expression needs an explicit target-type) 3. Var不能用于在同一行上实例化多个变量。
可以找到更多的细节,可以找到由空指针建议的这里。
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.数组初始化程序是不允许的,可以通过找到尼古拉建议的这里来获得更多详细信息。
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)https://stackoverflow.com/questions/49210591
复制相似问题