在dagger2的帮助下,我制作了一个简单的应用程序,告诉汽车是两轮车或四轮车,但是如果我运行这个应用程序,错误就会发生,并且这个错误没有绑定,我也使用了@Named注释,但是错误一次又一次地出现。
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()
}
}发布于 2022-03-30 01:00:13
您的类FW在构造函数旁边没有@Inject注释。我认为必须用这种方式来定义达格知道该怎么做
class FW @Inject constructor() : CarType {
override fun whichCar() {
Log.d("Type", "whichCar: Four wheeler")
}
}另外,您的函数tellCar2可能应该以这样的方式定义:
@Provides
@Named("four"
fun tellCar2(fw: FW) : CartType {
return fw
}由于您使用的是接口,所以也可以在抽象模块中使用@Binds,因此可以直接绑定接口的正确实现。查看本文:https://medium.com/mobile-app-development-publication/dagger-2-binds-vs-provides-cbf3c10511b5或此:https://dagger.dev/api/2.21/dagger/Binds.html
https://stackoverflow.com/questions/71604507
复制相似问题