Can Java 10 type inference for local variables infer void?

只谈情不闲聊 提交于 2019-12-08 23:39:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!