Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java 10 type inference for local variables infer void?

Tags:

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.

like image 316
mrek Avatar asked Mar 22 '18 12:03

mrek


People also ask

What's new in Java 10 local variable type inference?

Local Variable Type Inference is one of the most evident change to language available from Java 10 onwards. It allows to define a variable using var and without specifying the type of it. The compiler infers the type of the variable using the value provided. This type inference is restricted to local variables.

Why local variable type inference should be used?

This is especially worthwhile if the type is parameterized with wildcards, or if the type is mentioned in the initializer. Using var can make code more concise without sacrificing readability, and in some cases it can improve readability by removing redundancy.

Does Java support type inference?

Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable.

How does type inference work in Java?

Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned.


1 Answers

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

like image 195
ZhekaKozlov Avatar answered Sep 22 '22 21:09

ZhekaKozlov