vkelman
vkelman

Reputation: 1621

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 }

What is the purpose of this syntax?

Upvotes: 34

Views: 8841

Answers (1)

Max Farsikov
Max Farsikov

Reputation: 2763

This syntax gives Kotlin great DSL capabilities, it makes functions look like language constructions. For example:

with(car) {
   startUp()
   goToDestination()
}

Here with looks like it is language construction, whereas it is a simple function, receiving lambda as the last parameter.

And this leads to such elegant things like Kotlin HTML DSL

Upvotes: 30

Related Questions