All lessons

Power Tools: Lambdas & Collection Functions

10 min · Kotlin

Write inline lambdas and transform lists with map and filter.

Kotlin · Power Tools: Lambdas & Collection Functions0/5 cleared

Enemy 1 of 5

A lambda is a small, unnamed function you can define right where you need it, without a separate fun declaration. Kotlin's lambda syntax is { params -> expression }: parameters (with their types, if not inferrable), an arrow, then the body. You can assign a lambda to a val and call it exactly like an ordinary function — square(6) works the same whether square was defined with fun or as a lambda.

Lambdas matter because they let you hand a small piece of custom behavior to another function, without writing a whole separate named function for a one-off transformation. This is exactly what .map { } and .filter { } (below) are built around: instead of writing a manual loop with an if inside it, you describe the transformation inline as a lambda and let the collection function do the looping for you.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36