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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With