Local Variable Type Inference: Declare var, not war
In this article, I will try to explain 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.
Where it can be used
- Local variable initializers
- Indexes in the enhanced forloop
- Locals declared in a traditional forloop
- Resource variables of the try-with-resources statement
- Formal parameters of implicitly typed lambda expressions. (Support added in Java 11)
The following code snippet shows some valid examples.
Where it cannot be used
- Method parameters
- Method return types
- Local variable declarations without any initialization
- Cannot use null for initialization
I have tried to explain in the below code snippet what compiler error will come if it is used in a not supported way.
What's the benefit?
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 related to readability then some folks will like it and some will hate it. So if during a code review someone says that he 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 by clicking the link in the image below:
You can continue reading some of my previous articles.