How to Push to a GitHub Repository in IntelliJ
Lombok's @Builder is a powerful feature that replaces repetitive builder pattern code with a single annotation. However, when using @Builder, you might encounter the following warning message when you set an initial value for a field:
java: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.
Before solving the problem, it's important to understand why Lombok ignores the initial value of the field.
When a class is annotated with @Builder, Lombok generates a separate inner Builder class (e.g., UserBuilder) at compile time. This is the class we use through the .builder() method.
The key is that the fields of the original class and the fields of the Builder class exist in different spaces.
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class User {
private String name;
private int age = 18; // Default value for the 'User' object
}
In the code above, age = 18 is the default value for when a User object is created. However, the age field in the UserBuilder class, which is created when User.builder() is called, doesn't know about this value. Therefore, the UserBuilder's age field is initialized to the default value for an int, which is 0, and the 18 we specified is ignored.
This is precisely why Lombok warns that it "will ignore the initializing expression entirely."
The most common solution, as the warning message kindly suggests, is to use the @Builder.Default annotation. This annotation tells Lombok, "Apply this default value to the Builder class's field as well."
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class User {
private String name;
@Builder.Default // << Add this annotation
private int age = 18;
}
Now, if you don't set the age value separately through User.builder(), Lombok will use the initial value (18) of the field annotated with @Builder.Default as the default.
finalThe second suggestion in the warning message is to make the field final. This method is used when the field's value should never change after the object is created.
import lombok.Builder;
import lombok.Getter;
@Getter
@Builder
public class User {
private String name;
private final int age = 18; // << Add the final keyword
}
Declaring a field as final has the following characteristics:
The field must be initialized either at declaration or in the constructor.
@Builder will not generate a setter method like age() for this field in the Builder class. In other words, you cannot change this value through the builder.
Therefore, if the age field should always be 18 and doesn't need to be changed via the builder, final is an appropriate solution.
Comments
Post a Comment