Java Lombok | Declaring final Variables - val Variables

val Variables

When you define a variable with the val type, Lombok infers an appropriate type from the assigned value and declares the variable as final.

package com.devkuma.tutorial.lombok;

import lombok.val;

import java.util.Arrays;
import java.util.HashMap;

public class ValTutorial {

    public static void main(String... args) {
        val list = Arrays.asList("devkuma", "araikuma", "kimkc");
        list.forEach(System.out::println);

        val map = new HashMap<String, Long>();
        map.put("hoge", 1L);

        map = null;
    }
}

In the source code above, you can see that the code declaring map with val also loads the normal type correctly.

lombok val variable

Variables defined with val are declared as final, so they cannot be reassigned.

lombok val variable

If you write and run the map = null; code, the following error occurs.

D:\dev\\java-lombok-tutorial\src\main\java\com\devkuma\tutorial\lombok\ValTutorial.java:17: error: cannot assign a value to final variable map
        map = null;
        ^