lambda - 尾随 lambda 语法 (Kotlin) 的目的是什么?

标签 lambda kotlin fold

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/

相关文章:

android - 如何在同一屏幕上显示两个 Activity ?

java - Eclipse Aether 未正确解析 `LATEST`

clojure - 为什么 fold 和 reduce 被认为是基本的——当然一切都是根据 cons 和 car 来定义的?

scala - RDD中是否有任何 Action 保持顺序?

java - lambda 表达式中使用的变量应该是最终变量或有效最终变量

c# - 如何用简单的英语解释这个 lambda 表达式?

C# 带有 include 的 lambda 限制

c++ - boost::remove_if 导致错误(只读变量不可赋值)

android - 使用 RecycleView 的多 View - Kotlin(Android) - 无法切换 View

string - Haskell Lambda 折叠