I was going through new features in java 10.
But I could not understand what is local-variable type inference?
Can someone please explain.
Now we can write var x = new HashMap<String,String>();
instead of a more verbose Map<String,String> x = new HashMap<String,String> ();
and the information about type is not duplicated. It is one step ahead of Java 7 type inference for generic instance creation , a.k.a. diamond.
Usage of var
is possible within a method's scope only (hence the name: local variable) and it is allowed only in the statements where the type can be inferred (hence the suffix: type inference).
Parsing a var
statement, the Java 10 compiler infers the type from the right hand side (RHS) expression. This means that the variable declared using var
needs to be immediately assigned and even this:
var readMe;
readMe = "notAGoodVariableName";
OR this:
var readMe = null;
is NOT allowed.
Also, please note that since it makes code a little less explicit, if used in statements like var x = getCapitalized('abc')
, it can create confusions for the code reader.
Finally, var
is not a keyword, but a reserved type name. Not being a keyword ensures that all the legacy applications don't break. But being a reserved type name still means that there would be a single breaking point and the legacy applications will have to rename all classes/interfaces which are named exactly as var while upgrading to Java 10 (a very rare and anti-naming-convention case).
There are some rules to be followed to use it correctly, hence read more at:
http://openjdk.java.net/jeps/286
https://developer.oracle.com/java/jdk-10-local-variable-type-inference