2017-04-13 133 views
1

我使用从库中的部分代码:https://github.com/Netflix-Skunkworks/rewrite如何用lambda调用多个类似签名的Kotlin方法?

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

None of the following functions can be called with the arguments supplied.

目标的方法有两个类似的特征:

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>): Refactor { 
     val r = refactor() 
     ops.accept(r) 
     return r 
    } 
} 

在科特林调用代码:

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

这与调用拉姆达是OK在Java中:

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

回答

1

您可以修复在科特林调用代码:要传递一个lambda用一个参数{ tx -> doSomething() },但接收器的拉姆达,没有争吵,预计在那里。

比较:(Refactor) -> Unittype for a function使用一个参数,而Refactor.() -> Unitfunction with receiver,它没有参数,而是被传递Refactor类型的接收器(this)。这些类型有时可以互换,但lambdas不会在它们之间隐式转换。

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

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

或者,叫过载与Consumer<Refactor>,可以明确地说:

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

SAM conversion是,显然,不可用,因为有几个功能参数的重载。

相关问题