-
Notifications
You must be signed in to change notification settings - Fork 0
Hilt β Using qualifiers
Devrath edited this page Oct 9, 2023
·
5 revisions
Contents |
---|
Observations |
Output |
Code |
- Here using the qualifier we can differentiate between two identical type instances belonging to different objects
- In the
Activity
you can see that thecat
is injected andannotated
with aqualifier
belonging toAmerican cat
. - This hilt will pick the American Instance belonging to the
Cat
interface.
Cat instance -> 166290303
American Cat Running
Contents |
---|
Qualifiers |
Implementation |
Modules |
Activity |
AmericanCat.kt
@Qualifier
annotation class AmericanCat()
PersianCat.kt
@Qualifier
annotation class PersianCat()
Cat.kt
interface Cat {
fun getName() : String
}
AmericanCatImpl.kt
class AmericanCatImpl @Inject constructor(): Cat {
override fun getName(): String {
return "American Cat Running"
}
}
PersianCatImpl.kt
class PersianCatImpl @Inject constructor() : Cat {
override fun getName(): String {
return "Persian Cat Running"
}
}
CatModule.kt
@InstallIn(ActivityComponent::class)
@Module
abstract class CatModule {
@Binds
@AmericanCat
abstract fun provideAmericanCat(impl: AmericanCatImpl) : Cat
@Binds
@PersianCat
abstract fun providePersianCat(impl : PersianCatImpl) : Cat
}
MyActivity.kt
@AndroidEntryPoint
class HiltQualifiersActivity : AppCompatActivity() {
private lateinit var binding: ActivityHiltQualifiersBinding
@AmericanCat
@Inject lateinit var cat : Cat
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHiltQualifiersBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListeners();
}
private fun setOnClickListeners() {
binding.apply {
initiateId.setOnClickListener {
PrintUtils.printLog("Cat instance -> "+cat.hashCode().toString())
PrintUtils.printLog(cat.getName())
}
}
}
}