我有一个与此类似的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函数注入实现?
答案 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
怎么办?