Marcello Galhardo
Marcello Galhardo

Reputation: 791

Provide a @Multibiding of an empty map of Providers with Dagger 2

My problem is: I'm trying to declare a multibind with the following signature: Map<Class<out Fragment>, @JvmSuppressWildcards Provider<Fragment>>. The multibind works as expected when I have an IntoMap inside my scope modules. However, this map might or might not be empty depending on the scope and for that reason, I'm explicitly declaring @Multibinds like the following to support empty maps as the documentation suggests:

@Module
abstract class FragmentModule {

    @Multibinds
    abstract fun fragmentProviderMap(): 
        Map<Class<out Fragment>, @JvmSuppressWildcards Provider<Fragment>>
}

However, this code is producing the following error message:

error: @Multibinds methods must return Map or Set

Investigating the source code of Dagger 2 I found this is proposital:

@Test
public void providerMap() {
    assertThatModuleMethod("@Multibinds abstract Map<String, Provider<Object>> providerMap();")
        .withDeclaration(moduleDeclaration)
        .hasError("@Multibinds methods must return Map<K, V> or Set<T>");
}

For reference purposes, you can find this code here.

I have two doubts:

  1. If Dagger 2 supports to provide "non-empty" maps of Provider<*> using multibinds, what could be the reason for not allowing an empty map with the same signature?

  2. Is there any way to bypass this limitation and support empty maps of Provider<*>? This would save me a lot of boilerplate and unnecessary @Inject repetition.

Thank you for your attention.

Upvotes: 3

Views: 1588

Answers (1)

peterwhy
peterwhy

Reputation: 249

From a single map multibind definition, Dagger can inject both (the Kotlin equivalents of) Map<K, V> and Map<K, Provider<V>>.

Maybe you are just looking for

@Multibinds
abstract fun fragmentProviderMap(): 
    Map<Class<out Fragment>, @JvmSuppressWildcards Fragment>

?

See "Map Multibindings" and "Declaring multibindings" in Dagger Multibindings.

Upvotes: 1

Related Questions