代码之家  ›  专栏  ›  技术社区  ›  Maxim

函数中包含和不包含“suspend”lambda的“重载解析歧义”

  •  0
  • Maxim  · 技术社区  · 6 年前

    看看这个例子:

    fun f(block: suspend () -> Unit) {
        println("with suspend")
    }
    
    fun f(block: () -> Unit) {
        println("without suspend")
    }
    
    fun main() {
        f(suspend {
        })
    
        // This call cause compilation error:
        // Error:(16, 5) Kotlin: Overload resolution ambiguity:
        // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
        // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
        //
        // f({
        // })
    
        // This call cause compilation error:
        //
        // Error:(25, 5) Kotlin: Overload resolution ambiguity:
        // public fun f(block: () -> Unit): Unit defined in root package in file Main.kt
        // public fun f(block: suspend () -> Unit): Unit defined in root package in file Main.kt
        //
        // f {
        // }
    }
    

    suspend lambda中的关键字和不带的关键字)。

    问题:

    1) 如何调用第一个或第二个函数?如你所见,我可以用 暂停 暂停 关键字。

    2) 可以重写 f(suspend {}) 具有 trailing lambda (例如,使用 f suspend {} )?

    1 回复  |  直到 6 年前
        1
  •  3
  •   ardenit    6 年前

    1) 您可以通过一些变通方法调用第二个函数。例如,

    val foo = {}
    f(foo)
    

    f({}.also{})
    

    或者更短:

    f({}!!)
    

    将使用非挂起参数调用函数。在这些情况下,lambda是在函数参数上下文之外声明的,因此默认情况下它不可挂起。

    2) 尾部lambda语法不支持显式 suspend 修饰符,所以必须使用括号来声明lambda是可挂起的。