What is the default for Optional data members in lombok using @Builder?

Suppose I have a class such as this :

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?


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:

public AnIdentifier(@NonNull String mandatoryIdPart, String optionalIdPart1, String optionalIdPart2) {
    this.mandatoryIdPart = mandatoryIdPart;
    this.optionalIdPart1 = Optional.ofNullable(optionalIdPart1);
    this.optionalIdPart2 = Optional.ofNullable(optionalIdPart2);

Leave a Reply

Your email address will not be published. Required fields are marked *