I am trying to understand Java 10 Local Variable Type Inference. I seem to understand what it is, but I do not see any advantage from this. So I was wondering what is the idea behind introducing this feature. These are few of my observations. Please correct me if I am wrong here.
For example, (unlike other languages) I can not just declare a variable like this
I need to initialize it(But cannot initialize to null). So I don't really see any advantage whatsoever.
One of the other arguments I saw is that previously we had to declare a variable like this with its explicit types.
Map<User, String> userChannels = new HashMap<>();
Now I can do it like this
var userChannels = new HashMap<User, String>();
With modern day IDE's(like IntelliJ IDEA) and their support for code completion. I cannot think of any added advantage that this brings to the table(in the above context).
Some of the other points I read were that
Polymorphic code doesn’t play nice with var.
And also I cannot use var for non denotable types like Anonymous class.
Given all these, why was it necessary to introduce this feature? Can someone please clarify If I am missing something here.
One of the reasons is that it makes your code shorter and easier to read. Consider the following example, where you will use the variable only once or twice after the declaration.
ReallyLongClassNameBecauseBigEnterpriseProject reallyLongClassAbv = new ReallyLongClassNameBecauseBigEnterpriseProject(foo); OtherAnnoyingLongClassName otherAnnoyingLongClassName = reallyLongClassAbv.getOtherAnnoyingLongClassName();
If the variable name has the same name than the class (or a shortened name because you can deduce the class by the context or by the constructor), then the class name doesn't add much info. But if you write
var reallyLongClassAbv = new ReallyLongClassNameBecauseBigEnterpriseProject(foo); var otherAnnoyingLongClassName = reallyLongClassAbv.getOtherAnnoyingLongClassName();
It's already nicer and faster to read, and since you already have the class name, you don't lose any info. On a small bonus, your variable names are even aligned!
You might think that it doesn't make a big difference, but in my experience, I have worked in projects full of those statements and I really wished I didn't have to read two or three times the class name at each declaration. The
var keyword could increase the information/text ratio and make your code less verbose.
NOTE : to make it clear, even with
var, you should still avoid to give uselessly long names to your class, but sometimes you don't have the choice or it comes from another library.
As stated in the comments, you could have a look at the JEP to have a more complete answer and the Style Guidelines for Local Variable Type Inference by Stuart Marks.