Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 595
Marcello Galhardo Avatar asked Jan 30 '26 17:01

Marcello Galhardo


1 Answers

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.

like image 127
peterwhy Avatar answered Feb 02 '26 07:02

peterwhy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!