Skip to content

NULL_VALUE_IN_MAP

Googler edited this page Aug 12, 2020 · 1 revision

NULL_VALUE_IN_MAP

Summary

Guice will throw NULL_VALUE_IN_MAP error when null is added into a MapBinder.

Guice internally uses ImmutableMap to store the entries added into the MapBinder and ImmutableMap does not allow null values.

Example:

final class FooModule extends AbstractModule {
  @ProvidesIntoMap
  @StringKey("first")
  Foo provideFirstFoo() {
    // FooFactory.createFoo returns nullable values
    return FooFactory.createFoo();
  }
}

Guice will throw NULL_VALUE_IN_MAP error in the above example if FooFactory.createFoo returns null.

Common causes

Adding null by mistake

If you don't intend to store null in the MapBinder, simply make sure that null is never being returned for values in the map:

final class FooModule extends AbstractModule {
  @ProvidesIntoMap
  @StringKey("first")
  Foo provideFirstFoo() {
    Foo foo = FooFactory.createFoo();
    if (foo == null) {
      return new DefaultFooImpl();
    }
    return foo;
  }
}

Using null as absent value

If you want to distinguish between a key is not in the map from a key that in the map but maps to an absent value, then consider using Optional:

final class FooModule extends AbstractModule {
  @ProvidesIntoMap
  @StringKey("first")
  Optional<Foo> provideFirstFoo() {
    return Optional.fromNullable(FooFactory.createFoo());
  }
}

The resulting map that you can inject will be Map<String, Optional<Foo>> instead of Map<String, Foo>.

Clone this wiki locally