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 πŸ˜‰

Screen Shot 2018-01-07 at 3.37.09 PM

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.

Screen Shot 2018-01-07 at 3.53.33 PM

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

Screen Shot 2018-01-07 at 3.09.28 PM

Screen Shot 2018-01-07 at 3.09.55 PM

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


Screen Shot 2018-01-07 at 3.19.10 PM

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

Screen Shot 2018-01-07 at 4.10.20 PM

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.

Screen Shot 2018-01-10 at 9.08.33 PM

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

Screen Shot 2018-01-10 at 9.12.19 PM

This one turned out to be a bug in inspection and it has been since fixed.

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!

One thought on “Local Variable Type Inference in Java 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s