Annotation Interface MapKey
Every provider method annotated with @Provides
and @IntoMap
must also have an
annotation that identifies the key for that map entry. That annotation's type must be annotated
with @MapKey
.
Typically, the key annotation has a single member, whose value is used as the map key.
For example, to add an entry to a Map<SomeEnum, Integer>
with key
SomeEnum.FOO
, you could use an annotation called @SomeEnumKey
:
@MapKey
@interface SomeEnumKey {
SomeEnum value();
}
@Module
class SomeModule {
@Provides
@IntoMap
@SomeEnumKey(SomeEnum.FOO)
Integer provideFooValue() {
return 2;
}
}
class SomeInjectedType {
@Inject
SomeInjectedType(Map<SomeEnum, Integer> map) {
assert map.get(SomeEnum.FOO) == 2;
}
}
If unwrapValue
is true, the annotation's single member can be any type except an
array.
See dagger.multibindings
for standard unwrapped map key annotations for keys that are
boxed primitives, strings, or classes.
Annotations as keys
If unwrapValue()
is false, then the annotation itself is used as the map key. For
example, to add an entry to a Map<MyMapKey, Integer>
map:
@MapKey(unwrapValue = false)
@interface MyMapKey {
String someString();
MyEnum someEnum();
}
@Module
class SomeModule {
@Provides
@IntoMap
@MyMapKey(someString = "foo", someEnum = BAR)
Integer provideFooBarValue() {
return 2;
}
}
class SomeInjectedType {
@Inject
SomeInjectedType(Map<MyMapKey, Integer> map) {
assert map.get(new MyMapKeyImpl("foo", MyEnum.BAR)) == 2;
}
}
(Note that there must be a class MyMapKeyImpl
that implements MyMapKey
in
order to call Map.get(Object)
on the provided map.)
- See Also:
-
Optional Element Summary
Modifier and TypeOptional ElementDescriptionboolean
True to use the value of the single member of the annotated annotation as the map key; false to use the annotation instance as the map key.
-
Element Details
-
unwrapValue
boolean unwrapValueTrue to use the value of the single member of the annotated annotation as the map key; false to use the annotation instance as the map key.If true, the single member must not be an array.
- Default:
- true
-