如何在Guice中绑定Kotlin函数

时间:2018-01-21 20:49:19

标签: kotlin guice

我有一个与此类似的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&lt; ? super java.lang.Integer,kotlin.Unit&gt;被约束了。

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

2 个答案:

答案 0 :(得分: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<? super java.lang.Integer, **? extends** kotlin.Unit>

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

答案 1 :(得分:0)

如果您注射Function1<Int,Unit>代替(Int) -> Unit怎么办?