如何在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 

然而,

 bind(object : TypeLiteral>() {}).toInstance({}) 

注册一个types的kotlin.jvm.functions.Function1 kotlin.jvm.functions.Function1

改变bindbind(object : TypeLiteral>() {}).toInstance({})去除返回types的变化允许Guice正确注入函数。