Lambdas

Lambdas, Trailing Lambda Syntax and Higher-Order Functions

A lambda is a function literal in braces whose last expression is its result: JavaScript's b => b.price < 20 is { b -> b.price < 20 }, and a one-parameter lambda can use the implicit name it. A higher-order function takes or returns a function. The listings in the rest of this section compile together with this file:

Catalog.kt: BookNest's six books, shared by the listings in this sectionKotlin
data class Book(val title: String, val price: Double, val rating: Double, val inStock: Boolean)
val catalog = listOf(
  Book("The Quiet Harbor", 14.99, 4.6, true),
  Book("Patterns of the Deep Web", 39.50, 4.3, true),
  Book("Salt and Saffron", 24.00, 4.8, false),
  Book("Small Steps to Big Summits", 18.75, 4.1, true),
  Book("The Clockmaker's Paradox", 16.20, 4.5, true),
  Book("Gardens in Glass", 21.30, 4.4, true),
)
A higher-order function and the trailing lambda syntaxKotlin
fun totalOf(books: List<Book>, include: (Book) -> Boolean): Double =
  books.sumOf { if (include(it)) it.price else 0.0 }
fun main() {
  val cheap = catalog.filter({ book: Book -> book.price < 20.0 })   // full form
  val cheap2 = catalog.filter { it.price < 20.0 }                  // trailing lambda, it
  println("${cheap == cheap2} ${cheap2.map { it.title }}")
  println("%.2f".format(totalOf(catalog) { it.inStock && it.rating >= 4.5 }))
}
Output
true [The Quiet Harbor, Small Steps to Big Summits, The Clockmaker's Paradox]
31.19

The trailing lambda rule: when the last parameter is a function, the lambda may follow the closing parenthesis, and empty parentheses can then be dropped. totalOf(catalog) { ... } and Compose 234 's Button(onClick = { ... }) { Text("Add") } both use it. A lambda can read and modify the local vars it captures, as JavaScript closures do and Java lambdas cannot.