Hazel T
Hazel T

Reputation: 949

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

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.

Upvotes: 19

Views: 22273

Answers (3)

JafarKhQ
JafarKhQ

Reputation: 8734

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.

Upvotes: 19

JeanValjean
JeanValjean

Reputation: 17713

Another way to go is to use @Builder(toBuilder = true)

@Builder(toBuilder = true)
public class XYZ {
    private String x = "X";
    private String y = "Y";
    private String z = "Z";
}

and then you use it as follows:

new XYZ().toBuilder().build();

With respect to the accepted answer, this approach is less sensible to class renaming. If you rename XYZ but forget to rename the inner static class XYZBuilder, then the magic is gone!

It's all up to to you to use the approach you like more.

Upvotes: 3

ntalbs
ntalbs

Reputation: 29438

You have to provide the builder class like the below:

@Builder
public class XYZ {
    private String x;
    private String y;
    private String z;

    private static class XYZBuilder {
        private String x = "X";
        private String y = "Y";
        private String z = "Z";
    }
}

Then the default value for x, y, z will be "X", "Y", "Z".

Upvotes: 4

Related Questions