Local Variable Type Inference: Declare Var, Not War

Java is changing rapidly, and with the six-month release cycle, we are getting new features to try with every release. In Java 10, local variable type inference was added. It was basically aimed at reducing boilerplate code and improving readability when declaring local variables with initializers.

Programs must be written for people to read and only incidentally for machines to execute
Harold Abelson

Introduction to Lombok

Java is often criticized for being unnecessarily verbose when compared with other languages. Lombok provides a bunch of annotations that generate boilerplate code in the background, removing it from your classes, and, therefore, helping to keep your code clean. Less boilerplate means more concise code that’s easier to read and maintain. In this post, I’ll cover the Lombok features I use more regularly and show you how they can be used to produce cleaner, more concise code.

Local Variable Type Inference: val and var

Lots of languages infer the local variable type by looking at the expression on the right-hand side of the equals. Although this is now supported in Java 10+, it wasn’t previously possible without the help of Lombok. The snippet below shows how you have to explicitly specify the local type: