- Inside the
@Module
class, mark different methods with@Named(SOME_STRING_ID)
. - At site of injection as well, use
@Named(SOME_STRING_ID)
. TheSOME_STRING_ID
passed in the bracket will be used to differentiate which injection goes where.
// ======================================================================== // Main dependency // to inject class RandomNumberClass @Inject constructor(val base: Int) { val value = (Math.random()*100).toInt() * base } // ======================================================================== // Module defining // @Named parameters @InstallIn(ActivityComponent::class) @Module class DIModule(){ @Named("n1") @Provides fun getRandomNumber1(): RandomNumberClass{ return RandomNumberClass(3) } @Named("n2") @Provides fun getRandomNumber2(): RandomNumberClass{ return RandomNumberClass(5) } } // ======================================================================== // Class needing dependency as // CONSTRUCTOR INJECTION class TestClassAdd @Inject constructor( @Named("n1") private val n1: RandomNumberClass, // Corresponds to RandomNumberClass(3) @Named("n2") private val n2: RandomNumberClass // Corresponds to RandomNumberClass(5) ) { fun getStringAddition() = "Number 1: ${n1.value}, base: ${n1.base}, " + "Number 2: ${n2.value}, base: ${n2.base}; Addition: ${n1.value + n2.value}" }
- Declare different
annotation class
-es - Instead of using
@Named
, just use the class name as annotation.
Sample code
// ======================================================================== // Annotation classes // used as "markers" @Qualifier annotation class n1 @Qualifier annotation class n2 // The @Qualifier part may be optional // ======================================================================== // Module using above // annotation classes // to differentiate // instances of dependencies @InstallIn(ActivityComponent::class) @Module class DIModule(){ @n1 @Provides fun getRandomNumber1(): RandomNumberClass{ return RandomNumberClass(3) } @n2 @Provides fun getRandomNumber2(): RandomNumberClass{ return RandomNumberClass(5) } } // ======================================================================== // Class needing dependencies as // CONSTRUCTOR INJECTION class TestClassAdd @Inject constructor( @n1 private val n1: RandomNumberClass, // Corresponds to RandomNumberClass(3) @n2 private val n2: RandomNumberClass // Corresponds to RandomNumberClass(5) ) { fun getStringAddition() = "Number 1: ${n1.value}, base: ${n1.base}, " + "Number 2: ${n2.value}, base: ${n2.base}; Addition: ${n1.value + n2.value}" }