android - 使用 Dagger 2 提供函数依赖

标签 android dependency-injection kotlin functional-programming dagger-2

我想使用 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/

相关文章:

安卓工作室 3.2.1 ArtifactResolveException : Could not resolve all artifacts for configuration ':classpath'

android - IBM 工作灯 : Push Notification and Badge

javascript - WebView加载HTML但不显示

c# - 在同一个 Asp.Net Core 2 解决方案中将 DbContext 注入(inject)类库项目

android - Firebase Auth 返回一个神秘的错误 uid

android - VIEW PAGER 如何更改 View 堆栈中的页面顺序

c# - 使用 IOption 的类的实例化

java - Spring Boot 测试类可以重用应用程序上下文以更快地运行测试吗?

reflection - 如何在Kotlin中声明一组可反射的函数?

android - 使用 camera2 api 在前置摄像头中全屏录制视频