我正在尝试学习 dagger 2,试图将基本的 java 示例转换为 kotlin 但无法这样做,因为我遇到了以下错误...
错误:Dagger 不支持注入(inject)私有(private)字段 私有(private) com.example.Engine 引擎;
这是运行良好的 Java 代码,
public class Car {
private Engine engine;
private Wheel wheel;
@Inject
public Car(Engine engine, Wheel wheel) {
this.engine = engine;
this.wheel = wheel;
}
}
具有 2 个依赖项的 Car.java 类。
public class Engine {
@Inject
Engine(){}
}
public class Wheel {
@Inject
Wheel(){}
}
这是我的 Kotlin 代码:-
class Car(@Inject var engine: Engine, @Inject val wheels: Wheels) {
fun drive(){
Log.d("CAR","<<<<<< DRIVING >>>>>")
}
}
class Engine @Inject constructor() {}
class Wheels @Inject constructor() {}
@Component
interface CarComponent {
fun getCar() : Car
}
这是生成的代码
public final class Car {
@org.jetbrains.annotations.NotNull()
@javax.inject.Inject()
private com.toi.roboelectric.Engine engine;
@org.jetbrains.annotations.NotNull()
@javax.inject.Inject()
private final com.toi.roboelectric.Wheels wheels = null;
public final void drive() {
}
@org.jetbrains.annotations.NotNull()
public final com.toi.roboelectric.Engine getEngine() {
return null;
}
public final void setEngine(@org.jetbrains.annotations.NotNull()
com.toi.roboelectric.Engine p0) {
}
@org.jetbrains.annotations.NotNull()
public final com.toi.roboelectric.Wheels getWheels() {
return null;
}
public Car(@org.jetbrains.annotations.NotNull()
com.toi.roboelectric.Engine engine, @org.jetbrains.annotations.NotNull()
com.toi.roboelectric.Wheels wheels) {
super();
}
}
最佳答案
请将 Car Class 更新为
class Car @Inject constructor(var engine: Engine,val wheels: Wheels) {
fun drive(){
Log.d("CAR","<<<<<< DRIVING >>>>>")
}
关于android - 主构造函数的 Kotlin Dagger2 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59272967/