如何在Guice中绑定Kotlin函数
我有一个类似于这样的Kotlin类:
class MyClass @Inject constructor(val work: (Int) -> Unit)) { ... }
bind
和@Provides
都没有工作:
class FunctionModule : AbstractModule() { override fun configure() { bind(object : TypeLiteral<Function1>() {}).toInstance({}) } @Provides fun workFunction(): (Int) -> Unit = { Unit } } }
我不断收到错误:
没有实现kotlin.jvm.functions.Function1 被绑定。
如何使用Guice为Kotlin函数注入实现?
函数types被编译到Function
接口的实例中,具体的情况是Function1
。
所以,基本上你的types可以写成: Function1
。
如果你注入Function1
而不是(Int) -> Unit
?
tl; dr – 使用:
bind(object : TypeLiteral>() {}) .toInstance({})
在课堂里
class MyClass @Inject constructor(val work: (Int) -> Unit)) { ... }
参数work
有一个types(至少根据Guice):
kotlin.jvm.functions.Function1 super java.lang.Integer, kotlin.Unit>
然而,
bind(object : TypeLiteral>() {}).toInstance({})
注册一个types的kotlin.jvm.functions.Function1 super java.lang.Integer, **? extends** kotlin.Unit>
kotlin.jvm.functions.Function1 super java.lang.Integer, **? extends** kotlin.Unit>
改变bind
到bind(object : TypeLiteral
去除返回types的变化允许Guice正确注入函数。