Java 11 in IntelliJ IDEA 2018.2
The next version of Java is due out in September, and IntelliJ IDEA 2018.2 is ready for it. The main code feature in Java 11 is Local-Variable Syntax for Lambda Parameters – Java 10 gave us the ability to use the
var keyword for variables inside methods, now Java 11 lets us use this in lambda expressions:
BiConsumer<Processor, String> consumer = (var x, var y) -> x.process(y);
At first glance, although this removes the type information from:
BiConsumer<Processor, String> consumer = (Processor x, String y) -> x.process(y);
it’s actually not very compelling when you consider Java 8 already let us remove the type information altogether:
BiConsumer<Processor, String> consumer = (x, y) -> x.process(y);
But one of the cases where we might want to use
varinstead of the full type is if we wanted to apply an annotation to the parameter. Annotations require us to declare the full type:
BiConsumer<Processor, String> consumer = (@NotNull Processor x, @Nullable String y) -> x.process(y);
With the ability to use
varon parameters in a lambda expression, this can be shortened in Java 11 to:
BiConsumer<Processor, String> consumer = (@NotNull var x, @Nullable var y) -> x.process(y);
IntelliJ IDEA supports this change as you’d expect, allowing the
varkeyword in the lambda. But IntelliJ IDEA 2018.2 also helps migrate the code to this updated syntax. If, for example, you were using annotations in a lambda expression, the inspection for removing the “redundant parameter types” will replace the types with
Along with updates for the use of
var in Java 11, IntelliJ IDEA 2018.2 also has some improvements for working with
var. Holding down Ctrl/⌘ and hovering over the
var keyword will show the type of the variable:
Like any other type, we can click here and navigate to the declaration, or we can use Ctrl+B/⌘B to navigate to the declaration via
var. We can also use Quick Documentation (Ctrl+Q/F1) or Quick Definition (Ctrl+Shift+I/⌥Space) on
var to see the type.
It’s important to remember when working with this new syntax that all relevant type information needs to be on the right of the equals sign since the left side no longer declares the type. There are two inspections that have been updated to reflect this.
Firstly, IntelliJ IDEA 2018.2 understands that while sometimes an initializer is not required for a variable with an explicit type, variables created with
var will use an initial value to determine the type. Therefore any “redundant initializer” warning that applies to explicit type variables is not shown for
Similarly, the removal of an array type is not suggested for
var since it’s required:
In summary, IntelliJ IDEA 2018.2 is not only able to help when using Java 10 features, it’s ready to help us start coding with Java 11 before it’s even released!
Subscribe to Blog updates
Thanks, we've got you!