Kotlin - 括号外的lambda参数

Kotlin - lambda argument outside parenthesis

具有以下功能

fun functionOne(element: Int, func1: (index: Int) -> Unit) {
    println("element=$element")
    func1(element)
}

我可以这样称呼它:

functionOne(element = 123, func1 = {index -> println("index: $index")})

没有编译器抱怨

functionOne(123,  {index -> println("index: $index")})

现在编译器建议 Lambda argument should be moved out of parentheses

functionOne(123) { index -> println("index: $index") }

没有抱怨

但是,除非我没弄对,否则这个行为仅限于一个 lambda 参数,即

fun functionTwo(element: Int, func1: (index: Int) -> Unit, func2: (index: Int) -> Unit) {
    println("element=$element")
    func1(element)
    func2(element)
}

我可以这样打电话

functionTwo(123, { index -> println("index: $index")},  { index -> println("index2: $index")})

但是这个不编译

functionTwo(456) {index -> println("index: $index"} { index -> println("index2: $index")})

能否确认一下,或者让我知道将 lambda 参数移出括号

谢谢!

根据 documentation,只能将尾随 lambda 放在括号外:

Passing trailing lambdas

According to Kotlin convention, if the last parameter of a function is a function, then a lambda expression passed as the corresponding argument can be placed outside the parentheses:

val product = items.fold(1) { acc, e -> acc * e }

Such syntax is also known as trailing lambda.

If the lambda is the only argument in that call, the parentheses can be omitted entirely:

run { println("...") }

这意味着您不能将 second-to-last lambda 表达式移出括号,因此您不能将多个 lambda 表达式移出括号。