Reputation: 551
Suppose I have a class such as this :
@Builder
class AnIdentifier {
@NonNull //to indicate required to builder
private String mandatoryIdPart;
private Optional<String> optionalIdPart1;
private Optional<String> optionalIdPart2;
}
When a client creates an object using the builder generated by lombok for this class and does not set the optional parts, what are they set to? Also does the client have to pass a value wrapped in Optional or just the value to the builder for the optional parts?
Upvotes: 4
Views: 3395
Reputation: 5090
As of Lombok 1.16.16 you can do the following, to default it to Optional.empty()
@Builder.Default private Optional<String> optionalIdPart1 = Optional.empty()
see https://projectlombok.org/features/Builder
Until recently Intellij had issues with this which may have put some developers off, but they have been now been resolved
Upvotes: 4
Reputation: 551
Here's what I tried out :
public static void main(String[] args) {
AnIdentifier id = AnIdentifier.builder().mandatoryIdPart("added")
.optionalIdPart1(Optional.of("abs")).build(); //line 1
id.optionalIdPart2.isPresent(); //line2
}
Firstly line2 generated a NPE so optionalIdPart2 was set to null not Optional.empty()
Secondly from line1, setting the optional value required putting the string in an Optional, lombok doesn't take care of that.
So use a constructor such as this with the annotation:
@Builder
public AnIdentifier(@NonNull String mandatoryIdPart, String optionalIdPart1, String optionalIdPart2) {
this.mandatoryIdPart = mandatoryIdPart;
this.optionalIdPart1 = Optional.ofNullable(optionalIdPart1);
this.optionalIdPart2 = Optional.ofNullable(optionalIdPart2);
}
Upvotes: 1