typestar

Lambdas in Kotlin

Function values in braces, with it standing in for a lone parameter.

fun main() {
    // A lambda is a value; its last expression is the result.
    val toMiles = { km: Double -> km * 0.621 }
    println(toMiles(21.0))

    // A sole lambda argument moves outside the parentheses, and a
    // single parameter goes by the name it.
    val legs = listOf(8.4, 11.2, 6.9)
    println("Longest leg: ${legs.maxByOrNull { it }} km")
    legs.forEachIndexed { day, km ->
        println("Day ${day + 1}: $km km")
    }
}

How it works

  1. { km: Double -> km * 0.621 } is a value assigned like any other.
  2. A sole lambda argument moves outside the parentheses: maxByOrNull { it }.
  3. forEachIndexed hands the lambda two named parameters at once.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
401
Tokens
82
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 2 of 3 in Functions, step 8 of 27 in Language basics.

← Previous Next →

Lambdas in other languages