Reputation: 7133
I am using lombok's builder. To assign the default value to some variables I am trying to use
@Builder.Default
But the problem is that on using the above annotation, I am no longer able to initialize that value through builder as compiler says can not resolve method while trying to initialize the variable through builder.
So, essentially what I am looking for is a way to set default values and still be able to override when initiating through builder.
Upvotes: 4
Views: 3369
Reputation: 1143
My team has been struggling with this annotation failing to work in certain IDE's. Our workaround is to define a constructor with the @Builder
annotation that sets the defaults if no value was given. For example:
public class ExampleClass {
private final OtherClass otherClassField;
@Builder
public ExampleClass(OtherClass otherClass) {
// if otherClass is null, use a default value
otherClassField = otherClass != null ? otherClass : new OtherClass();
}
}
As a note, if your class has primitive type fields, you'll need to use the primitive-wrapper types for the constructor arguments to be able to continue to use a null
value to indicate falling back to the default.
You can also change the constructor access level to private
to allow instances of this class to only be created using a builder.
Upvotes: 4