如何在 Guice 中绑定 Kotlin 函数

How to bind a Kotlin Function in Guice

我有一个与此类似的 Kotlin class:

class MyClass @Inject constructor(val work: (Int) -> Unit)) { ... }

bind@Provides 都不工作:

class FunctionModule : AbstractModule() {

    override fun configure() {
        bind(object : TypeLiteral<Function1<Int, Unit>>() {}).toInstance({})
    }

    @Provides
    fun workFunction(): (Int) -> Unit = { Unit }
    }
}

我一直收到错误消息:

No implementation for kotlin.jvm.functions.Function1< ? super java.lang.Integer, kotlin.Unit> was bound.

如何使用 Guice 注入 Kotlin 函数的实现?

如果您要注入 Function1<Int,Unit> 而不是 (Int) -> Unit 怎么办?

tl;dr - 使用:

bind(object : TypeLiteral<Function1<Int, @JvmSuppressWildcards Unit>>() {})
    .toInstance({})

在class

class MyClass @Inject constructor(val work: (Int) -> Unit)) { ... }

参数 work 的类型(至少根据 Guice)为:

kotlin.jvm.functions.Function1<? super java.lang.Integer, kotlin.Unit>

然而,

bind(object : TypeLiteral<Function1<Int, Unit>>() {}).toInstance({})

注册了一个类型 kotlin.jvm.functions.Function1<? super java.lang.Integer, **? extends** kotlin.Unit>

bind 更改为 bind(object : TypeLiteral<Function1<Int, **@JvmSuppressWildcards** Unit>>() {}).toInstance({}) 删除 return 类型的差异允许 Guice 正确注入函数。