【问题标题】:How to call Kotlin method with more than one similar signature with lambda?如何使用 lambda 调用具有多个类似签名的 Kotlin 方法?
【发布时间】:2017-04-13 10:27:01
【问题描述】:

我正在使用这个库中的一些代码: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>): Refactor {
        val r = refactor()
        ops.accept(r)
        return r
    }
}

Kotlin 中的调用代码:

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

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

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

【问题讨论】:

    标签: java kotlin higher-order-functions overload-resolution


    【解决方案1】:

    您可以修复 Kotlin 中的调用代码:您正在传递一个带有一个参数 { tx -&gt; doSomething() } 的 lambda,但那里需要一个带有接收器且没有参数的 lambda。

    比较:(Refactor) -&gt; Unit 是带有一个参数的type for a function,而Refactor.() -&gt; Unit 表示function with receiver,它不接受任何参数,而是传递一个Refactor 类型的接收器(this)。这些类型有时可以互换,但 lambda 不会在它们之间隐式转换。

    所以,你可以这样称呼refactor

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

    或者,要使用Consumer&lt;Refactor&gt; 调用重载,您可以明确指定:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多