Kotlin 和 Groovy 都提供了一种编写高阶函数的方法,其中函数参数具有隐式接收器。
科特林版本
class KotlinReceiver {
fun hello() {
println("Hello from Kotlin")
}
}
class KotlinVersion {
fun withReceiver(fn: KotlinReceiver.() -> Unit) {
KotlinReceiver().fn()
}
}
// And then I can call...
val foo = KotlinVersion()
foo.withReceiver { hello() }
Groovy 版本
class GroovyReceiver {
void hello() {
println("Hello from Groovy")
}
}
class GroovyVersion {
void withReceiver(Closure fn) {
fn.resolveStrategy = Closure.DELEGATE_FIRST
fn.delegate = new GroovyReceiver()
fn.run()
}
}
// And then I can call...
def foo = new GroovyVersion()
foo.withReceiver { hello() }
我的目标是写withReceiver
Kotlin 中的函数,但从 groovy 调用它并且有{ hello() }
工作。不过,正如所写,Kotlin 生成的字节码如下
public final void withReceiver(@NotNull Function1 fn) { /* ... */ }
Groovy 将其视为带有参数的函数。换句话说,调用 Kotlin 的withReceiver
从 Groovy 开始,我必须这样做:
(new KotlinVersion()).withReceiver { it -> it.hello() }
为了让{ hello() }
没有it -> it.
,我必须添加一个重载,需要groovy.lang.Closure
作为其参数。
科特林版本
import groovy.lang.Closure
class KotlinVersion {
fun withReceiver(fn: KotlinReceiver.() -> Unit) {
KotlinReceiver().fn()
}
fun withReceiver(fn: Closure<Any>) = withReceiver {
fn.delegate = this
fn.resolveStrategy = Closure.DELEGATE_FIRST
fn.run()
}
}
随着过载的到位,给定KotlinVersion
实例称为foo
以下行适用于两种语言:
// If this line appears in Groovy code, it calls the Closure overload.
// If it's in Kotlin, it calls the KotlinReceiver.() -> Unit overload.
foo.withReceiver { hello() }
我试图保留该语法,但避免为我的 Kotlin 库定义的每个高阶函数编写额外的样板重载。是否有更好(更无缝/自动)的方法使 Kotlin 的带有接收器的函数语法可以从 Groovy 中使用,这样我就不必手动向每个 Kotlin 函数添加样板重载?
上面我的玩具示例的完整代码和编译指令是在 gitlab 上 https://gitlab.com/drmoose/so-how-can-i-call-with-receiver-from-groovy.