Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 966
vkelman Avatar asked Feb 01 '19 21:02

vkelman


1 Answers

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

like image 87
Max Farsikov Avatar answered Oct 10 '22 00:10

Max Farsikov