https://kotlinlang.org logo
#dagger
Title
# dagger
c

Chris Fillmore

05/13/2021, 7:09 PM
1. Hi folks. Question: Do I need to define a custom
@Component
in order to use map multibinding with Hilt? (e.g. as in Dagger https://dagger.dev/dev-guide/multibindings) I have the below sample code. Of course it doesn’t work, fails with
Dagger/MissingBinding
, since there is no provider for
Map<String, MyInterface
. But I offer it just to illustrate the question.
Copy code
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

  @Inject
  lateinit var implMap: Map<String, MyInterface>

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    Log.d("MainActivity", "implMap: $implMap")
  }
}

@Module
@InstallIn(ActivityComponent::class)
object MyModule {
  @Provides @IntoMap
  @StringKey("myimpl1")
  fun provideMyImpl1(): MyInterface {
    return MyImpl1("myArg")
  }
  @Provides @IntoMap
  @StringKey("myimpl2")
  fun provideMyImpl2(): MyInterface {
    return MyImpl2()
  }
}


interface MyInterface {
  fun myMethod()
}

class MyImpl1(private val myParam: String) : MyInterface {
  override fun myMethod() {}
}

class MyImpl2 : MyInterface {
  override fun myMethod() {}
}

@HiltAndroidApp
class MyApplication : Application()
r

Rafal

05/13/2021, 8:00 PM
Hi, you might need to add
@JvmSuppressWildcards
to your injected field
Copy code
@Inject
lateinit var implMap: Map<String, @JvmSuppressWildcards MyInterface>
c

Chris Fillmore

05/13/2021, 8:11 PM
Oh you’re right! I totally forgot. Thanks @Rafal