Issue
I have made a simple app that tells the car is a two-wheeler or four-wheeler with the help of dagger2 but an error will occur if I run the app and the error is binding is missing for this I have also used @Named annotation but the error is coming again and again.
MainActivity.kt
class MainActivity : AppCompatActivity() {
@Inject
lateinit var car: Car
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DaggerCarComp.builder().build().inject(this)
car.tellCarTypes()
}
}
Car.kt
class Car @Inject constructor(
@Named("two") val tw: TW,
val fw: FW
) {
fun tellCarTypes() {
tw.whichCar()
}
}
CarComp.kt
@Component(modules = [CarModule::class])
interface CarComp {
fun inject (mainActivity: MainActivity)
}
CarType.kt
interface CarType {
fun whichCar()
}
class TW @Inject constructor() : CarType {
override fun whichCar() {
Log.d("Type", "whichCar: Two wheeler")
}
}
class FW : CarType {
override fun whichCar() {
Log.d("Type", "whichCar: Four wheeler")
}
}
CarModule.kt
@Module
class CarModule {
@Provides
@Named("two")
fun tellCar(tw: TW) : CarType {
return tw
}
@Provides
@Named("four")
fun tellCar2() : CarType {
return FW()
}
}
Solution
Your class FW does not have the @Inject annotation alongside his constructor. I think it has to be defined this way so Dagger know what to do
class FW @Inject constructor() : CarType {
override fun whichCar() {
Log.d("Type", "whichCar: Four wheeler")
}
}
Also your function tellCar2
should probably be defined in this way :
@Provides
@Named("four"
fun tellCar2(fw: FW) : CartType {
return fw
}
Since you are using an interface, you could also use @Binds in an abstract module and so you can directly bind the correct implementation of the interface regarding your needs. Check this article : https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5 or this : https://dagger.dev/api/2.21/dagger/Binds.html
Answered By - Fcps
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.