局部变量的Java 10类型推断可以推断出无效吗? [英] Can Java 10 type inference for local variables infer void?
问题描述
使用Java 10,我们可以使用类型推断。
With Java 10, we can use type inference.
String s1 = "hello"; // before Java 10
var s2 = "hello"; // now
然而,有一件事我们以前做不到:有类型的变量的空隙即可。
However, there is one thing which we couldn't do before: have variables of type void.
因此,在以前的版本中,我们根本无法定义变量类型 void
。但现在我们可以将返回 void
的方法的结果分配给变量:
So, in previous versions we simply couldn't define the variable type void
. But now we can assign result of method returning void
to the variable:
void emptyMethod() { }
...
void v1 = emptyMethod(); // won't compile
var v2 = emptyMethod(); // no problem at all
问题是 - 为什么它甚至可以编译,它的目的是什么?你有这个奇怪的用例吗?
The question is - why does it even compile, what purpose does it serve? Do you have any use case for this strange thing?
类型变量 void
没有方法,它不能是甚至用作方法的参数。
Variable of type void
has no methods, it cannot be even used as a parameter of a method.
推荐答案
为什么你认为它编译?它不编译:
Why do you think it compiles? It doesn't compile:
> javac Main.java
Main.java:5: error: cannot infer type for local variable v2
var v2 = emptyMethod(); // no problem at all
^
(variable initializer is 'void')
1 error
您可能使用IntelliJ IDEA,对吗? IDEA目前没有检测到这种错误。有一个错误: https://youtrack.jetbrains.com/issue/IDEA-188623
You probably use IntelliJ IDEA, do you? IDEA currently does not detect such kind of an error. There is a bug for that: https://youtrack.jetbrains.com/issue/IDEA-188623
这篇关于局部变量的Java 10类型推断可以推断出无效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!