1

By default, immutables.io will create empty collections if none are supplied.

@Value.Immutable
public abstract class MyTestPojo {
    public abstract List<String> myList();
}

The following will create the object with an empty collection:

MyTestPojo pojo = ImmutableMyTestPojo.builder()
        .build();

However, if the value is explicitly set to null, immutables will throw NPE.

MyTestPojo pojo2 = ImmutableMyTestPojo.builder()
        .myList(null)
        .build();

This could be avoided by allowing nulls with @Nullable. This would result in the collection being null. I would like this case to gracefully handle null and convert it to an empty collection.

Community
  • 1
  • 1
Patrick
  • 90
  • 2
  • 8
  • 1
    I'm assuming you're not actually providing `null` as a parameter to `myList`, but rather a variable that happens to be null. If this is indeed the case, is anything preventing you from initializing that variable to be an empty list` – Henrik Aasted Sørensen Apr 27 '20 at 10:17
  • That is correct! I am not actually passing null, but rather a variable. The approach you mentioned is what I a currently doing (which is working fine). Only issue I have is I have to repeat the null check and create empty collection in quite a few places, and it is possible that someone can forget to do this in the future. I'd like to avoid this mistake ever being made in the future. – Patrick May 13 '20 at 16:44

1 Answers1

1

I suggest you look into the normalization feature, which makes it possible to perform some modifications before the final instance is returned:

@Value.Immutable
public abstract class MyTestPojo {
    @Nullable
    public abstract List<String> myList();

    @Value.Check
    protected MyTestPojo check() {
        if ( myList() == null ) {
            return ImmutableMyTestPojo.copyOf(this).withMyList();
        }

        return this;
    }
}

Note that the myList property is annotated with @Nullable. The check will override the null value with an empty list during instantiation.

Henrik Aasted Sørensen
  • 6,966
  • 11
  • 51
  • 60