What is the val keyword in Lombok?

What is Lombok?

Project Lombok is a Java library that helps reduce boilerplate codeA section of code that is repeated in multiple places with little variation.. Java is a verbose language where repetitive code like getters, setters, and so on can be avoided. Lombok reduces the boilerplate code with its annotations that get plugged during the build process.

Lombok can easily be added to the project by adding it as one of the dependencies.

For a Gradle project, we can add the following two lines to the dependencies section of the build.gradle file:

compileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'

For a Maven project, we can add the following lines to the dependencies section of the pom.xml file:

<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
</dependencies>

The val keyword

The @val keyword is used to define local variables final without specifying the type. Refer to the following examples:

Vanilla Java

Using Lombok

final String platform = "name";

val platform = "name";

final ArrayList<String> names = new ArrayList<String>();

val names = new ArrayList<String>();

Since the variables declared are final, their modification will lead to compile-time errors.

For example, val platform = "educative";. If we assign a new value to the variable platform by doing the platform = "edpresso";, the build will fail to indicate a new value and cannot be assigned to a final variable.

Code

Let’s look at the code below:

import lombok.val;
import java.util.HashMap;

public class Main {

    public static void main(String[] args){
        val map = new HashMap<String, String>();
        map.put("hi", "hello");
        map.put("educative", "edpresso");
        for (val entry : map.entrySet()) {
            System.out.printf("%s: %s\n", entry.getKey(), entry.getValue());
        }

        // map = new HashMap<String, String>();
    }
}

Explanation

  • Lines 1 to 2: We import the val and HashMap dependencies.
  • Line 7: A HashMap called map is defined using the val keyword.
  • Line 8: We add an entry to map.
  • Line 9: We add an entry to map.
  • Lines 10 to 12: The contents of the map are printed using a for loop. The loop invariable is defined using val keyword as the type is inferred.
  • Line 14: If we try to reassign map to a new HashMap, the build fails as the map is a final variable.

Free Resources