@var

Since

@var was introduced as experimental feature in lombok v1.16.12.

Experimental

Experimental because:

  • This feature is very controversial.
  • There is JEP 286 that should make the @var obsolete.
Current status: uncertain - Currently we feel this feature cannot move out of experimental status.

Overview

The @var has the same mission as the @val annotation but modifable.

With Lombok

01 import java.util.ArrayList;
02 import lombok.var;
03 
04 public class ValExample {
05   public String example() {
06     var example = new ArrayList<String>();
07     example.add("Hello, World!");
08     final var foo = example.get(0);
09     return foo.toLowerCase();
10   }
11 
12   public void example2() {
13     var list = new ArrayList<String>();
14     list.add("zero");
15     list.add("one");
16     list.add("two");
17     for(var i = 0; i < list.size(); ++i) {
18       System.out.printf("%d: %s\n", i, list.get(i));
19     }
20   }
21 }

Vanilla Java

01 import java.util.ArrayList;
02 import lombok.var;
03 
04 public class ValExample {
05   public String example() {
06     ArrayList<String> example = new ArrayList<String>();
07     example.add("Hello, World!");
08     final String foo = example.get(0);
09     return foo.toLowerCase();
10   }
11 
12   public void example2() {
13     ArrayList<String> list = new ArrayList<String>();
14     list.add("zero");
15     list.add("one");
16     list.add("two");
17     for(int i = 0; i < list.size(); ++i) {
18       System.out.printf("%d: %s\n", i, list.get(i));
19     }
20   }
21 }

Supported configuration keys:

lombok.val.flagUsage = [allow] (default: not set)
Lombok will flag any usage of var as an error if not configured.

Small print

For compound types, the most common superclass is inferred, not any shared interfaces. For example, bool ? new HashSet() : new ArrayList() is an expression with a compound type: The result is both AbstractCollection as well as Serializable. The type inferred will be AbstractCollection, as that is a class, whereas Serializable is an interface.

In ambiguous cases, java.lang.Object is inferred.