Dependency injection with Hilt-4 (Annotation)
2 min readApr 5, 2021
Outline :
Annotation used for sorting when using an interface in more than one class. Determines which action we will do first.
A qualifier is an annotation that you use to identify a specific binding for a type when that type has multiple bindings defined.
Scope :
Create a second Implementer class
class SecondInterfaceImplementor
@Inject constructor() : MyInterface
{
override fun myPrintFunction(): String {
return "My Second Interface Implementor"
}
}
Adding Annotation’s values which are Qualifier and Retention
interface MyInterface {
fun myPrintFunction() : String
}
@InstallIn(SingletonComponent::class)
@Module
class MyModule{
@FirstImplementor
@Singleton
@Provides
fun providerFunction():MyInterface{
return InterfaceImplementor()
}
@SecondImplementor
@Singleton
@Provides
fun secondProviderFunction():MyInterface {
return SecondInterfaceImplementor()
}
@Singleton
@Provides
fun gSonProvider() : Gson{
return Gson()
}
}
//These are explain that you would use annotation
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class FirstImplementor
@Qualifier
@Retention(AnnotationRetention.BINARY)
annotation class SecondImplementor
Edit ClassExample class and show them in MainActivity
class ClassExample
@Inject constructor(@FirstImplementor private val myInterfaceImplementor: MyInterface,
private val gson : Gson,
@SecondImplementor private val mySecondInterfaceImplementor: MyInterface) {
fun myFunction() : String {
return "Working: ${myInterfaceImplementor.myPrintFunction()}"
}
fun mySecondFunction() : String {
return "Working: ${mySecondInterfaceImplementor.myPrintFunction()}"
}
}
Result :
println(myClass.myFunction())
println(myClass.mySecondFunction())//Logcat
System.out: My interface Implementor
System.out: My Second Interface Implementor
I would like to thank Atıl Samancıoglu and Google who helped me understand this topic.
Atıl Samancıoglu : https://atilsamancioglu.com/
https://developer.android.com/training/dependency-injection/hilt-android#hilt-modules