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,所以,只能重命名类或接口