-
Notifications
You must be signed in to change notification settings - Fork 0
Hilt β Interface Injection
Devrath edited this page Oct 9, 2023
·
5 revisions
Contents |
---|
Observations |
Output |
Code |
- If you observe the
Religion
class type has the object ofBuddhism
Religion instantiated by the hilt. - Now when you inject the
Religion
into the activity, You get theBuddhism
reference.
Religion instance -> 226246109
BuddhismReligion -> Printed
Contents |
---|
Implementation |
Modules |
Activity |
Religion.kt
interface Religion {
fun getReligionName() : String
}
JainismReligion.kt
class JainismReligion @Inject constructor() : Religion {
override fun getReligionName(): String {
return "JainismReligion -> Printed"
}
}
Hinduism.kt
class Hinduism {
init {
PrintUtils.printLog("Hinduism constructor is invoked !")
}
}
BuddhismReligion.kt
class BuddhismReligion @Inject constructor() : Religion {
override fun getReligionName(): String {
return "BuddhismReligion -> Printed"
}
}
ReligionModule.kt
@InstallIn(ActivityComponent::class)
@Module
object ReligionModule {
@Provides
fun providesHinduism() : Hinduism { return Hinduism() }
@Provides
fun providesReligion() : Religion { return BuddhismReligion() }
}
MyActivity.kt
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityHiltInterfaceInjectionBinding
@Inject lateinit var religion : Religion
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHiltInterfaceInjectionBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListeners();
}
private fun setOnClickListeners() {
binding.apply {
initiateId.setOnClickListener {
PrintUtils.printLog("Religion instance -> "+religion.hashCode().toString())
PrintUtils.printLog(religion.getReligionName())
}
}
}
}