I want inject interface implementation in abstract class constructor and use it in child class.
I have compile time errors:
Error:Gradle: Dagger does not support injection into private fields
Error:Gradle: Example.A cannot be provided without an @Provides-annotated method.
Error:Gradle: Example.B cannot be provided without an @Inject constructor or from an @Provides-annotated method.
Error:Gradle: Execution failed for task ':app:compileDemoDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Example in kotlin.
object Example {
interface IData {
fun foo() {
}
}
class Data : IData {
}
@Module
class DataModel {
@Provides
fun data(): IData = Data()
}
@Singleton
@Component(modules =
arrayOf(DataModel::class)
)
interface Injector {
fun inject(a: A)
fun inject(b: B)
}
val graph: Injector = DaggerInjector.builder().
dataModel(DataModel()).
build()
abstract class A {
@Inject var data: IData ? = null
public open fun setUp() {
graph.inject(this)
}
}
open class B : A() {
override fun setUp() {
super.setUp()
data!!.foo()
}
}
fun bar() {
val a = B()
a.setUp()
}
}
versions:
Here is case. Decompiled java
public static class A {
@Inject
@Nullable
private Example.IData data;
@Nullable
protected final Example.IData getData() {
return this.data;
}
protected final void setData(@Nullable Example.IData <set-?>) {
this.data = <set-?>;
}
public void setUp() {
Example.INSTANCE.getGraph().inject(this);
}
}
From the error message, I think the problem is with this line:
@Inject var data: IData ? = null
The backing field for this property is private
, and this is what the error says. Usually the lateinit
keyword is used for such cases:
@Inject lateinit var data: IData
lateinit
is one of several modifiers that expose the backing field directly with the property's access level (public
here), making it visible to Dagger-generated classes.