问题
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.
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?
Variable of type void
has no methods, it cannot be even used as a parameter of a method.
回答1:
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
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
来源:https://stackoverflow.com/questions/49429056/can-java-10-type-inference-for-local-variables-infer-void