-2

I was going through new features in java 10.

But I could not understand what is local-variable type inference?

Can someone please explain.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
  • 2
    You couldn't do a little bit of searching? – Kayaman Mar 27 '18 at 09:01
  • 3
    @Kayaman To be fair, the duplicate is not exact, but if a question can be answered with "read the docs", it's not worth asking anyway. – user202729 Mar 27 '18 at 09:09
  • 1
    I would also suggest, if you actually want to go through the features in Java10, please follow its [official release notes](http://www.oracle.com/technetwork/java/javase/10-relnote-issues-4108729.html) and not end up tentatively spamming here. – Naman Mar 27 '18 at 09:22

1 Answers1

6

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

gargkshitiz
  • 2,130
  • 17
  • 19
  • Suggestion - It's always good to reference official docs like [this](http://openjdk.java.net/jeps/286) and another one like [this](http://openjdk.java.net/projects/amber/LVTIstyle.html) instead. – Naman Mar 27 '18 at 09:24
  • Sure, I did just that. After saving, saw your comment. Thanks for the suggestion :) – gargkshitiz Mar 27 '18 at 09:26