Declare final local variables in Java using Lombok

 Why we should mark local variables as final in Java?

In the cases where we do not want a local variable to change its value, it is a good practice to mark them as final

A final local variable serves as a warning when you “accidentally” try to modify a value and also provides information to the compiler that can lead to better optimization of the class file.

Some developers do not prefer this approach as it cutters the code with final keyword. This post is not debating whether to use final keyword or not, but explains an alternative, I stumbled upon, for making local variables as final.

Marking local variables as final using Lombok's val keyword.

Project Lombok provide a keyword val that can be used to mark local variables as final. Similar feature is available in Kotlin programming language, however in a more extensive way. Using Lombok's val keyword, might help us un-clutter the code.

See below examples:

Simple Java class with final local variables:

Java class using Lombok:

To add Lombok to your Maven project use this dependency:


Post a Comment