Reputation: 3076
I try to use the new Dagger Android injection thing that works so far.
Now I want to extend it to my needs.
In my MainActivityModule
I added a TestModule
:
@Module
abstract class MainActivityModule {
@ActivityScope
@ContributesAndroidInjector(modules = arrayOf(TestModule::class))
internal abstract fun contributeMainActivityInjector(): MainActivity
}
The TestModule
is really simple:
@Module
internal abstract class TestModule {
@Provides
internal fun provideTest(): String {
return "foo bar"
}
}
But I get this error: TestModule must be set
I looked into the generated source code but can't find a hint what I have to do. I searched for this at Google too but found only simple examples :-(
What have I forgotten? You can find the complete app at GitHub.
Edit
As Jeff Bowman sayed the provideTest()
needs to be static. When I create a Java class like this:
@Module
public class TestModule {
@Provides
static String provide() {
return "foo bar";
}
}
it works.
So the final question: How to make this in Kotlin? This doesn't work:
@Module
internal abstract class TestModule {
companion object {
@Provides
@JvmStatic
internal fun provideTest(): String {
return "foo bar"
}
}
}
So I need another way to create a static method.
Upvotes: 4
Views: 920
Reputation: 3734
An alternative solution, that's a bit cleaner in case you need to mock / replace dependencies in tests, would be to avoid making the class abstract, and keep the provides not static, like this:
@Module
internal class TestModule {
@Provides
internal fun provideTest(): String {
return "foo bar"
}
}
Upvotes: 0
Reputation: 3076
yeh I found a solution :-)
The Kotlin way to get a static
method is to put the method in a companion object
but now Dagger throws an error that the @Provides
can only be used in a @Module
. To fix this I annotated the companion object
too
@Module
internal abstract class TestModule {
@Module
companion object {
@Provides
@JvmStatic
internal fun provideTest(): String {
return "foo bar"
}
}
}
Upvotes: 5