Reputation: 2864
I am working on Android application. I am using Dagger2 for dependency injection. I am able to use this library but I don't know how to inject nested classes.
public class Parent {
@Inject
public Parent()
{}
public String getParent() {
return "fifth";
}
class ParentSubClass{
@Inject
public ParentSubClass(){
}
public String getParentSubClass(){
return "subfifth";
}
}
}
class SomeTest{
@Inject
Parent.ParentSubClass subclass;
}
I know injecting parent class but how to create object for parentsubclass
Upvotes: 1
Views: 1266
Reputation: 7368
@Inject
constructors are not supported on inner classes as Dagger tells us in the logcat:
error: @Inject constructors are invalid on inner classes public ParentSubClass()
If you'd like to provide your inner class, you should provide it using a @Provides
method:
@Provides
internal fun provideSubclass() : ParentSubClass {
return Parent().ParentSubClass()
}
Upvotes: 2
Reputation: 6116
The nested class in the example has access to all of its parent properties, so you can inject all dependencies you need in the parent and later use those in the subclass.
Upvotes: 0