Lombok @Builder.Default isn't working for @Value object if to set null

Viewed 2970

I'm trying to get immutable Object that sets default value to all null fields. So my object is:

import lombok.Builder;
import lombok.Value;

@Value
@Builder
public class Test {
    @Builder.Default
    String name = "default";
}

and I expect these two tests to pass:

assert Test.builder().build().name == "default"
assert Test.builder().name(null).build().name == "default"

but second one isn't passing.

How can I tell lombok not to set actually null in such case? I have value that comes from another service and it's nullable. I want to use default value if it came null to me.

1 Answers

Lombok's @Builder.Default remembers whether the corresponding builder setter method has been called or not. This allows explicitly overwriting the default value even with null. There is no built-in way to "unset" the value.

There are two ways to solve this:

  1. Remove the default value and @Builder.Default from name. Then manually implement an all-args constructor that checks whether the parameter name is null and assign the default value in that case.

  2. Customize the builder setter method such that passing null will unset it:

    public static class TestBuilder {
        public TestBuilder name(String name) {
            this.name$value = name;
            this.name$set = name != null;
            return this;
        }
    }

I suggest you use the latter approach, because then you won't have to modify your manual all-args constructor every time you add or remove a field in that class.

Related