【问题标题】:Restrictions on using Local-Variable Type Inference in java 10在 java 10 中使用局部变量类型推断的限制
【发布时间】:2018-08-19 00:27:02
【问题描述】:

Java 10 引入了Local-Variable Type Inference 功能JEP-286

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

但是使用它有一些限制。

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

【问题讨论】:

标签: java java-10


【解决方案1】:

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

更多细节可以找到herenullpointer 建议

   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.不允许使用数组初始化器 更多细节可以找到here 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)

【讨论】:

  • 你可能想添加可以添加数组初始化器。
  • ...和方法参考以及在JEP-286 风险和假设中抽样...以及 why 有趣的部分似乎每个都太广泛。
  • 感谢@Nicolai 添加了数组初始化器
  • var 理论上如何应用于返回类型?
  • @shmosel var foo() { return ""; }(你说“理论上”)...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多