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

Nir*_*ane 6 java java-10

Java 10引入了局部变量类型推断功能JEP-286.

我们可以使用Local-Variable Type Inference var作为保留类型名称

但是使用它有一些限制.

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

Nir*_*ane 6

1.顾名思义,你可以用它只能用于局部变量.

2.本地类型推断不能用于没有初始化器的变量

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

情况1:

  var xyz = null;
            ^
  (variable initializer is 'null')
Run Code Online (Sandbox Code Playgroud)

案例2:

var xyz;
            ^
  (cannot use 'val' on variable without initializer)
Run Code Online (Sandbox Code Playgroud)

案例3:

   var xyz = () -> { };
            ^
  (lambda expression needs an explicit target-type) 
Run Code Online (Sandbox Code Playgroud)

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

更多细节可以在这里找到 由nullpointer建议

   var X=10,Y=20,Z=30 // this is not allowed 
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

4.不允许使用数组初始化程序更多详细信息可以在此处找到Nicolai建议

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

5. 不允许使用方法参考

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

  • ...和方法参考以及[JEP-286](http://openjdk.java.net/jeps/286)中的风险和假设......以及**为什么**每个人的有趣部分他们似乎太宽泛了. (5认同)
  • @shmosel`var foo(){return""; }(你说"*理论上*")...... (4认同)
  • 您可能希望添加可添加数组初始值设定项. (2认同)