In this article, I will explain the Java 10 new feature: local variable type inference using reserved type name var.
Java is changing rapidly and with the new release cycle of 6 months, we are getting new features to try with every release. In Java 10 a new feature Local-Variable Type Inference was added. It was basically aimed at reducing boilerplate code and improving the readability when declaring local variables with initializers.
Programs must be written for people to read, and only incidentally for machines to execute~Harold Abelson
Let's understand this with an example. Following code is written without using Local-Variable Type Inference.
After refactoring as per Java 10 local variable type inference.
In the above-refactored code, the compiler can infer the declared type itself by looking at the RHS declaration.
These are just some of the examples to make you understand the feature and how we can use local variable type inference.
Now let's understand where local variable type inference can be used and where it cannot be.
The following code snippet shows some valid examples.
I have tried to explain in the below code snippet what compiler error will come if it is used in a not supported way.
If you ask me personally I think developers should use it judiciously. It is understood that there is excitement whenever a feature comes in and you definitely want to give it try. But you have to understand that we as a developer read code more often then we write it.
Since this is related to readability then some folks will like it and some will hate it. So if during a code review someone says that he/she is not able to get the declared type of var then it means that it is not very clear to others so maybe switching back to the old-fashioned way where we declare types explicitly is not that bad after all. Again in some situations declared type is quite obvious then you can skip the explicitly declared type and make use of the var.
In this article, we have covered what is Local-Variable Type Inference new Java 10 feature with some examples where it can be used and where it's not supported. You can further read these FAQs prepared by the OpenJDK team about Local-Variable Type Inference.
If you like what you just read then you can buy me a coffee.
You can continue your education by reading some of my previous articles.
Also published at https://dev.to/yrashish/declare-var-not-war-1ofi