我有一个类似于此的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<没有实现吗?超级java.lang.Integer,kotlin.Unit>被捆绑。
如何使用Guice为Kotlin函数注入实现?
发布于 2018-01-23 22:58:38
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就可以正确地注入函数。
发布于 2018-01-22 04:35:24
如果你要注入Function1<Int,Unit>而不是(Int) -> Unit怎么办?
https://stackoverflow.com/questions/48371583
复制相似问题