Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

lombok

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?

like image 757
Vitalii Avatar asked Dec 19 '17 09:12

Vitalii


People also ask

Can we use @data and @builder together?

6. Lombok @Data and @Builder together. If you use @Data annotation alone, public required-args constructor is generated. If you are using @Data and @Builder annotations together, all-args constructor (Package access level) is generated.

Does Lombok builder use constructor?

3. Use @Builder on Constructor Level. When we want to create a builder for specific fields, we should create a constructor with only those fields. Then when we put the @Builder annotation on the constructor, Lombok creates a builder class containing only the constructor parameters.

What is the difference between @data and @value in Lombok?

@Value is similar to the @Data annotation, but it creates immutable objects. It is a shortcut annotation which combines @FieldDefaults(makeFinal = true, level = AccessLevel. PRIVATE), @Getter, @AllArgsConstructor, @ToString and @EqualsAndHashCode. However, it doesn't have @Setter.


1 Answers

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.

like image 104
Michael A. Schaffrath Avatar answered Oct 05 '22 23:10

Michael A. Schaffrath