尾随 lambda 语法 (Kotlin) 的目的是什么?
What is the purpose of trailing lambda syntax (Kotlin)?
Passing a lambda to the last parameter
In Kotlin, there is a convention that if the last parameter of a
function accepts a function, a lambda expression that is passed as the
corresponding argument can be placed outside the parentheses:
val product = items.fold(1) { acc, e -> acc * e }
这个语法的目的是什么?
这种语法为 Kotlin 提供了强大的 DSL 功能,它使函数看起来像语言结构。例如:
with(car) {
startUp()
goToDestination()
}
这里with
看起来是语言构造,其实是一个简单的函数,接受lambda作为最后一个参数。
这导致了像 Kotlin HTML DSL
这样优雅的事情
Passing a lambda to the last parameter
In Kotlin, there is a convention that if the last parameter of a function accepts a function, a lambda expression that is passed as the corresponding argument can be placed outside the parentheses:
val product = items.fold(1) { acc, e -> acc * e }
这个语法的目的是什么?
这种语法为 Kotlin 提供了强大的 DSL 功能,它使函数看起来像语言结构。例如:
with(car) {
startUp()
goToDestination()
}
这里with
看起来是语言构造,其实是一个简单的函数,接受lambda作为最后一个参数。
这导致了像 Kotlin HTML DSL
这样优雅的事情