With the recent versions of dagger 2 one of the improvements made are the possibility of having static provide methods. Simply so:
@Provides
static A providesA() {
return A();
}
I was wondering how does one go about doing this in kotlin? I've tried
@Module
class AModule {
companion object {
@JvmStatic
@Provides
fun providesA(): A = A()
}
}
But I get the error message:
@Provides methods can only be present within a @Module or @ProducerModule
I'm guessing there's something going on here with the companion object, however I'm quite new to Kotlin and I'm unsure of how one can do this. Is it even possible?
Thanks!
I can't test it right now, but I think this should work:
Although I think zsmb13's solution is better, I found another solution which works
However, note that there will be two generated classes:
AModule_ProvidesAFactory
andAModule_Companion_ProvidesAFactory
rather than the oneAModule_ProvidesAFactory
class for the case with an object instead of a class with a companion objectFor the static only approach, I like the solution of zsmb13.
However, I came here because I wanted to combine
@Provides
and@Binds
within one module. This is not directly possible but with two nested modules (as Omar Al Halabi pointed out).I took a slightly different approach for combining
@Provides
and@Binds
:The differences are:
companion object
.abstract
modifier in both the class and the function.A great explanation which seems to be Google-approved is at https://github.com/google/dagger/issues/900
Specifically, see: