我有一个类似的 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 }
}
}
我不断收到错误:
no implementation for kotlin.jvm.functions.Function1<? super java.lang.Integer, kotlin.单位>被绑定。
如何使用 Guice 为 Kotlin 函数注入实现?
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 正确注入函数。
如果你注入Function1<Int,Unit>
而不是(Int) -> Unit
怎么办?