20

在 Java 10 中,我们可以使用类型推断。

String s1 = "hello"; // before Java 10
var s2 = "hello"; // now

然而,有一件事我们以前不能做:拥有void类型的变量。

因此,在以前的版本中,我们根本无法定义变量 type void。但是现在我们可以将方法返回void的结果分配给变量:

void emptyMethod() { }
...

void v1 = emptyMethod(); // won't compile
var v2 = emptyMethod(); // no problem at all

问题是 - 为什么它甚至可以编译,它的目的是什么?你有这个奇怪的东西的用例吗?

类型变量void没有方法,甚至不能作为方法的参数。

4

1 回答 1

32

为什么你认为它编译?它不编译:

> 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

于 2018-03-22T12:57:39.230 回答