Project Lombok is a Java library that helps reduce
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 is used to define local variables final without specifying the type. Refer to the following examples:
Vanilla Java | Using Lombok |
|
|
|
|
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.
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>();
}
}val and HashMap dependencies.HashMap called map is defined using the val keyword.map.map.map are printed using a for loop. The loop invariable is defined using val keyword as the type is inferred.map to a new HashMap, the build fails as the map is a final variable.