Kotlin's Lambda Syntax


Happy New Year! 🎉

I intend to start writing about some more complex Kotlin concepts, but I’d like to lay a bit of groundwork first.

Lambda Functions

Lambda functions are little chunks of code that can be passed around in functions [1]. They’re usually concise, single-minded, and anonymous.

The main benefit is that they can be executed by the function we pass them into. This gives the language space for a lot of declarative, functional APIs.

We’re usually saying, to the function we’re calling, something along the lines of:

“Map the collection to a new one using this lambda function.”

“Create a new collection containing only items filtered using this lambda function.”

Kotlin’s Syntax

When we have a function that takes in a lambda, we can pass it in directly, like we do in most programming languages.

listOf(1, 2, 3).map({ num -> num * num })

There is, however, a nice shortcut where we can omit the -> and use the implicit it parameter. The following is equivalent to the first example:

listOf(1, 2, 3).map({ it * it })

If the last parameter of the function we’re using (map, in this case) is a function, then we can place it outside of the parenthesis. If it’s the only parameter, we don’t even need parenthesis. This is a Kotlin convention.

listOf(1, 2, 3).map { it * it }

It's the same when a function has multiple parameters.

foo(a, { /* lambda function */ })
foo(a) { /* lambda function */ }