AnyCompiler

Lambdas and Higher-Order Functions

A lambda in Kotlin is written as { parameters -> body }, and when it has exactly one parameter, you can skip naming it and refer to it as it instead. filter and map are higher-order functions — functions that take another function as an argument — letting you chain transformations over a collection in a style that reads almost like a description of what you want.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val evenSquares = numbers.filter { it % 2 == 0 }.map { it * it }
    println(evenSquares)
}
Output
[4, 16, 36]

Next: objects and companion objects — Kotlin's replacement for Java's static.

Practice exercise

Given val numbers = listOf(1, 2, 3, 4), use filter and map to build a list of the squares of the even numbers, then print it.