Default field value with @Builder or @Getter annotation in Lombok

Hazel Troost :

I'm using Lombok @Builder annotation, but I'd like some of the String fields to be optional and default to "" to avoid NPEs. Is there an easy way to do this? I can't find anything.

Alternately, a way to customize @Getter to return a default value if the variable is null.

JafarKhQ :

Starting from version v1.16.16 they added @Builder.Default.

@Builder.Default lets you configure default values for your fields when using @Builder.

example:

@Setter
@Getter
@Builder
public class MyData {
  private Long id;
  private String name;

  @Builder.Default
  private Status status = Status.NEW;
}

PS: Nice thing they also add warning in case you didn't use @Builder.Default.

Warning:(35, 22) java: @Builder will ignore the initializing expression entirely. If you want the initializing expression to serve as default, add @Builder.Default. If it is not supposed to be settable during building, make the field final.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=456061&siteId=1