Local Variable Type Inference in Java 10

One handy feature that made the cut in JDK 10 release train is Local-Variable Type Inference (JEP-286). This language feature is part of project Amber, a successor to Project Coin 🙂

With more frequent releases planned for the Java platform, we could expect to see 2 feature releases this year, so March release will be 18.3 and September LTS release will be 18.9. No kidding, Java 10 build#37 shows the release date 😉

We can expect to see small improvements every six months, so developers don’t have to wait for more than 2 years to catch up with the language. One such productivity-oriented language feature coming in Java 10 is Local-Variable Type Inference (LVTI).
Intellij IDEA 2017.3 has experimental support for this feature.

To enable this feature in your IntelliJ Java project, set the language level to “X – Experimental Features” under Project Settings.

You can trigger this feature from their inspection too, which requires you to accept to their legal.

You can see it automatically detect code that can benefit from this syntactic sugar.

It also supports reverting to old behavior, all the good stuff you are used to with IntelliJ IDEA.

LTVI introduces a new context-sensitive keyword “var”, which technically is not a keyword, instead it is a restricted local variable type and cannot be used for type declarations. So, existing code which uses “var” in variable declarations or as a method name or package name will still be allowed, unlike class or interface name.

Here are some basic examples.

Here is another example involving lambda.

If you look at this example carefully, you’ll see our IntelliJ Lambda inspection kicks in for our anonymous inner class.

I replaced it with lambda, but it did not keep IntelliJ happy (of course, this is experimental!).

Support for Lambda Parameters is coming. In fact, there is an experimental support for this feature in lvti branch in amber repository. Maurizio explains the details in this post.

Happy learning folks!