Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 7]
Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)
Table of contents
Qualifiers in Hilt
Qualifiers in Hilt are used to disambiguate between multiple bindings of the same type. They allow us to differentiate between different implementations of an interface or class, ensuring that the correct dependency is provided when injecting.
To use qualifiers, we define our custom annotations and annotate the corresponding binding methods or fields in Hilt modules.
Example - Using Qualifiers in Hilt:
1. Define custom qualifiers:
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class FirstImplementation
@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class SecondImplementation
2. Create Hilt modules with qualified bindings:
@Module
@InstallIn(SingletonComponent::class)
object MyModule {
@Singleton
@FirstImplementation
@Provides
fun provideFirstDependency(): MyDependency {
return FirstImplementationDependency()
}
@Singleton
@SecondImplementation
@Provides
fun provideSecondDependency(): MyDependency {
return SecondImplementationDependency()
}
}
In this example, we define two custom qualifiers, @FirstImplementation
and @SecondImplementation
. Then, we create a Hilt module, MyModule
, with two different @Provides
methods, each annotated with a different qualifier.
3. Inject qualified dependencies:
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
@FirstImplementation
@Inject
lateinit var firstDependency: MyDependency
@SecondImplementation
@Inject
lateinit var secondDependency: MyDependency
// Use firstDependency and secondDependency as needed
}
In the Activity, we use the @FirstImplementation
and @SecondImplementation
qualifiers to indicate which implementation of MyDependency
should be injected for firstDependency
and secondDependency
, respectively.
By using qualifiers, we can easily switch between different implementations of the same type when injecting dependencies. This is particularly useful when we have multiple implementations of an interface or class and want to specify which one to use in different parts of our application.