【问题标题】:How to bind a Kotlin Function in Guice如何在 Guice 中绑定 Kotlin 函数
【发布时间】:2018-01-21 20:49:19
【问题描述】:

我有一个类似这样的 Kotlin 类:

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 }
    }
}

我不断收到错误:

没有实现 kotlin.jvm.functions.Function1 已绑定。

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

【问题讨论】:

  • 注意{ Unit }可以简化为{}

标签: kotlin guice


【解决方案1】:

tl;dr - 使用:

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

在课堂上

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&lt;? super java.lang.Integer, **? extends** kotlin.Unit&gt;的类型

bind 更改为bind(object : TypeLiteral&lt;Function1&lt;Int, **@JvmSuppressWildcards** Unit&gt;&gt;() {}).toInstance({}) 消除返回类型的差异允许 Guice 正确地注入函数。

【讨论】:

    【解决方案2】:

    如果你注入 Function1&lt;Int,Unit&gt; 而不是 (Int) -&gt; Unit 会怎样?

    【讨论】:

    • 这就是bind(object : TypeLiteral&lt;Function1&lt;Int, Unit&gt;&gt;() {}).toInstance({})(来自我的问题)所做的。它生成的错误显示在问题中。
    猜你喜欢
    • 2016-08-06
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2012-01-19
    • 2012-10-16
    • 2020-08-17
    相关资源
    最近更新 更多