JDK10中var分析

本文探讨了JDK10中引入的var关键字,它用于局部变量类型推断。文章提出关于var能否用于全局变量、方法返回值和参数的疑问,并引用官方文档解释其仅适用于局部变量。此外,文章还讨论了var与try-with-resources语句的结合使用,以及var作为已存在变量、方法或包名的影响,指出var是一个保留类型名称,不适用于类或接口的命名。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  jdk10中引入了var——Local-Variable Type Inference(局部变量类型推断),顾名思义,只能用做为局部变量。

  引出以下问题:

  1、为什么只能用做局部变量,全局变量、方法返回值、方法参数可以吗?

  2、除了书写方便,以降低可读性作为代价的var是否值得使用?

  3、之前老代码命名成var类的是否会起冲突?

  带着上面两个问题在网上找了一番答案,但都是根据自己的经验做的评判,并没有找到让我信服的答案。我决定去看看官方文档怎么说。

官方文档关于1的解释:

Action At A Distance   


官方文档关于2的解释:

Code such as that shown in the following example seems redundant and makes the code harder to read.

URL url = new URL("http://www.oracle.com/"); 
URLConnection conn = url.openConnection(); 
Reader reader = new BufferedReader(
    new InputStreamReader(conn.getInputStream()));

A new identifier named var is now available for local variables with non-null initializers. Using this identifier, the type of the variable is inferred from the context. The code from the previous example can be rewritten as shown in the following example:

var url = new URL("http://www.oracle.com/"); 
var conn = url.openConnection(); 
var reader = new BufferedReader(
    new InputStreamReader(conn.getInputStream()));

官方文档说下面的代码比上面的要简洁,好吧,不过我认为就上面的这个例子还是说服不了我。

然后估计官方自己也觉得说服不了自己,接着又举例:

var list = new ArrayList<String>();    // infers ArrayList<String>
var stream = list.stream();            // infers Stream<String>

var path = Paths.get(fileName);        // infers Path
var bytes = Files.readAllBytes(path);  // infers bytes[]

for (var counter=0; counter<10; counter++)  {...}   // infers int

try (var input = 
     new FileInputStream ("validation.txt")) {...}   // FileInputStream

然而我还是觉得作用不大,这里最后一行看到了个jdk7里面的语法:

try-with-resources——作用是省去了自己在finally里去关闭资源,只要实现了java.lang.AutoCloseable接口的对象,和实现了java.io.Closeable接口的对象,都可以当做资源使用


   官方文档关于3的解释:

    var is a reserved type name, not a keyword, which means that existing code that uses var as a variable, method, or package name is not affected. However, code that uses var as a class or interface name is affected and the class or interface needs to be renamed.

        官方文档说到var不是关键字,而是一个保留类型名称,而且不支持类或接口叫var,所以,只能重命名类或接口再见


    



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值