在java 10中使用局部变量类型推断的限制 [英] Restrictions on using Local-Variable Type Inference in java 10

查看:190
本文介绍了在java 10中使用局部变量类型推断的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Java 10 has introduce Local-Variable Type Inference feature JEP-286.

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

We can use Local-Variable Type Inference using var which is reserved type name

但使用它有一些限制。

有人可以总结在哪些情况下我不会能够使用var?

Can someone please summarise in which cases i will be not able to use var ?

推荐答案

1。顾名思义,你只能将它用于本地变量。

1. As the name suggests, you can use it only for local variables.

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

2. Local type inference cannot be used for variables with no initializers

例如,以下代码无法使用

e.g Below code will not work

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

3. Var can not used to instantiate multiple variables on same line

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

More details can be found here Suggested by 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建议

4. Array initializer is not allowed More details can by found here Suggested by 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)

这篇关于在java 10中使用局部变量类型推断的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆