-
Notifications
You must be signed in to change notification settings - Fork 1.7k
NULL_VALUE_IN_MAP
Googler edited this page Aug 12, 2020
·
1 revision
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.
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;
}
}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>.
-
User's Guide
-
Integration
-
Extensions
-
Internals
-
Releases
-
Community