Member-only story
Level Up Your Android Development with Custom Qualifier Annotations in Hilt
Dependency injection with Hilt simplifies Android development, but sometimes you need more control when dealing with multiple implementations of the same type. Custom qualifier annotations provide this power, acting as labels to differentiate between dependency bindings.
The Need for Qualifiers: Imagine scenarios with multiple loggers or, as we’ll explore, different ways to handle asynchronous tasks or interact with various APIs. Qualifiers ensure Hilt injects the precise dependency you need.
Creating Custom Qualifiers:
We can create a custom qualifier annotation by annotating an annotation class
with @Qualifier
and @Retention(AnnotationRetention.BINARY)
:
@Retention(AnnotationRetention.BINARY)
@Qualifier
annotation class MyCustomQualifier
Let’s break down this code:
@Retention(AnnotationRetention.BINARY)
: This standard Kotlin annotation specifies how long our custom annotation should be retained.BINARY
means it will be stored in the compiled.class
files but won't be available at runtime via reflection. This is generally sufficient for Hilt qualifiers.@Qualifier
: This annotation fromjavax.inject.Qualifier
marks our MyCustomQualifier annotation as a qualifier…