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这样优雅的事情
关于lambda - 尾随 lambda 语法 (Kotlin) 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487570/