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

Hazel Troost picture Hazel Troost · Oct 29, 2016 · Viewed 13.3k times · Source

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.

Answer

JafarKhQ picture JafarKhQ · Jul 27, 2017

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.