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

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

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

But there are some restrictions of using it.

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

解决方案

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

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

e.g Below code will not work

Case 1:

var xyz = null;

^

(variable initializer is 'null')

Case 2:

var xyz;

^

(cannot use 'val' on variable without initializer)

Case 3:

var xyz = () -> { };

^

(lambda expression needs an explicit target-type)

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

More details can be found here Suggested by nullpointer

var X=10,Y=20,Z=30 // this is not allowed

4: Var as Parameters

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. 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. Method reference is not allowed

var someVal = this::getName;

error: cannot infer type for local variable nameFetcher

(method reference needs an explicit target-type)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值