我想使用 Dagger 2 提供一个函数作为依赖:
@Module
class DatabaseModule {
@Provides
@Singleton
fun provideDatabase(application: Application, betaFilter: (BetaFilterable) -> Boolean): Database {
return Database(application, BuildConfig.VERSION_CODE, betaFilter)
}
@Provides
@Suppress("ConstantConditionIf")
fun provideBetaFiler(): (BetaFilterable) -> Boolean {
return if (BuildConfig.FLAVOR_audience == "regular") {
{ it.betaOnly.not() }
} else {
{ true }
}
}
}
不幸的是,它似乎不起作用:
[dagger.android.AndroidInjector.inject(T)] kotlin.jvm.functions.Function1<?
super com.app.data.BetaFilterable,java.lang.Boolean>
cannot be provided without an @Provides-annotated method.
我在这里错过了什么?
最佳答案
是的,这可以在 Kotlin 中完成。
You need to add @JvmSuppressWildcards at the injection site to ensure the signature matches. (source)
我写了以下内容来验证它:
import dagger.Component
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
class G constructor(val function: Function1<Int, Boolean>)
@Singleton
@Module
class ModuleB {
@Provides
fun intToBoolean(): (Int) -> Boolean {
return { it == 2 }
}
@JvmSuppressWildcards
@Provides fun g(intToBoolean: (Int) -> Boolean): G {
return G(intToBoolean)
}
}
@Singleton
@Component(modules = [ModuleB::class])
interface ComponentB {
fun g(): G
}
val componentB = DaggerComponentB.create()
val g = componentB.g()
println(g.function(2)) // true
println(g.function(3)) // false
背景:检查@Kiskae 的回复,问题似乎是当代码转换为 Java 字节码时,Kotlin 中函数类型的参数在其自身参数类型上变得逆变。如果这对您没有意义,请不要担心。使用我上面展示的技术不需要理解它。
关于android - 使用 Dagger 2 提供函数依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406171/