Default value in lombok. How to init default with both constructor and builder

Vitalii picture Vitalii · Dec 19, 2017 · Viewed 79.4k times · Source

I have an object

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo {
    private int id;
    private String nick;
    private boolean isEmailConfirmed = true;
}

And I initialize it in two ways

UserInfo ui = new UserInfo();
UserInfo ui2 = UserInfo.builder().build();

System.out.println("ui: " + ui.isEmailConfirmed());
System.out.println("ui2: " + ui2.isEmailConfirmed());

Here is output

ui: true
ui2: false

It seems that builder does not get a default value. I add @Builder.Default annotation to my property and my object now looks like this

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class UserInfo { 
    private int id;
    private String nick;
    @Builder.Default
    private boolean isEmailConfirmed = true;
}

Here is console output

ui: false
ui2: true

How can I make them both be true?

Answer

Michael A. Schaffrath picture Michael A. Schaffrath · Dec 19, 2017

My guess is that it's not possible (without having delomboked the code). But why don't you just implement the constructor you need? Lombok is meant to make your life easier, and if something won't work with Lombok, just do it the old fashioned way.

@Data
@Builder
@AllArgsConstructor
public class UserInfo { 
    private int id;
    private String nick;
    @Builder.Default
    private boolean isEmailConfirmed = true;
    
    public UserInfo(){
        isEmailConfirmed = true;
    }
}

Console output:

ui: true
ui2: true

Update
As of 01/2021, this bug seems to be fixed in Lombok, at least for generated constructors. Note that there is still a similar issue when you mix Builder.Default and explicit constructors.