如何调用与lambda多个相似签名Kotlin方法?

我正在使用这个库的一些代码: https : //github.com/Netflix-Skunkworks/rewrite

当我调用它的一个方法时,我遇到一个IDE错误:

所提供的参数都不能调用以下函数。

目标方法有两个相似的签名:

data class CompilationUnit(...){ fun refactor() = Refactor(this) fun refactor(ops: Refactor.() -> Unit): Refactor { val r = refactor() ops(r) return r } fun refactor(ops: Consumer): Refactor { val r = refactor() ops.accept(r) return r } } 

Kotlin的调用代码:

 val unit: CompilationUnit =... unit.refactor{ tx -> doSomeThing() } 

在Java中,这个lambda调用是可以的:

 CompilationUnit unit = .... unit.refactor(tx -> { doSomeThing() }); 

您可以在Kotlin中修复调用代码:您正在传递带有一个参数{ tx -> doSomething() }的lambdaexpression式,但是期望在那里使用带有接收器且不带参数的lambdaexpression式。

比较: (Refactor) -> Unit是带有一个参数的函数的types ,而Refactor.() -> Unit意味着带有接收者的函数 ,它不接受任何参数,而是传递一个types为Refactor的接收者( this )。 这些types有时是可以互换的,但是lambdas并不是隐含地在它们之间转换的。

所以,你可以调用它的refactor ,如下所示:

 val unit: CompilationUnit = ... unit.refactor { doSomeThing() // this code can also work with `this` of type `Refactor` } 

或者,要使用Consumer调用重载,可以显式指定:

 unit.refactor(Consumer { tx -> doSomething() }) 

隐式SAM转换显然不可用,因为有几个带有function参数的重载。