javaimmutables-library

Null collections converted to empty


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.


Solution

  • 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.