Lombok val variable

You can use val as the type of a local variable declaration instead of actually writing the type.

Points to be Remember:

  1. When you do this, the type will be inferred from the initializer expression.
  2. The local variable will also be made final.
  3. This feature works on local variables and on foreach loops only, not on fields(member variable).
  4. The initializer expression is required.
  5. It also reads generic types properly.


    val example = new ArrayList<String>();

same as:   final ArrayList<String> example = new ArrayList<String>();

val variable
val variable

package sample.lombok;import java.util.Arrays;import java.util.HashMap;import lombok.val;public class Main {    public static void main(String... args) {        val list = Arrays.asList("Tom", "Bob", "Riyo");        list.forEach(System.out::println);        val map = new HashMap<String, Long>();        map.put("Arjun", 1L);    }}