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

Niraj Sonawane:

Java 10引入了本地变量类型推断功能JEP-286

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

但是使用它有一些限制。

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

Niraj Sonawane:

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不能用于实例化同一行上的多个变量

更多详细信息可以在这里找到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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章