๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Lambdas

A lambda is a small unnamed block of code held in a value. A program can run that code later by using the value name.

A lambda stored in a value

The braces hold a small block that adds its two values. The name add runs that block at each call.

fun main() {
    val add = { a: Int, b: Int -> a + b }
    println(add(3, 4))
    println(add(10, 5))
}

The short name it

This lambda writes no parameter name of its own. it stands for the value the list hands over on each pass.

fun main() {
    val numbers = listOf(3, 4, 5)
    numbers.forEach { println(it * 2) }
}

forEach walks a list

forEach runs its lambda one time for each value in the list. The name before the arrow receives the current value.

fun main() {
    val names = listOf("Ana", "Bo", "Cy")
    names.forEach { name -> println("Hello, $name") }
}

Example

fun main() {
    val addTax = { price: Int -> price + 5 }
    val prices = listOf(10, 20, 30)
    prices.forEach { println(addTax(it)) }
}

Key points

  • Braces hold the code of a lambda.
  • Lambda parameters sit before the -> arrow inside the braces.
  • it: the short name for the single parameter when no name is written.
  • Use forEach to run a lambda once for each value in a list.

In this example, addTax is a lambda that adds 5 to its value. The list holds three prices. forEach hands each price to the lambda through it, one price at a time. The prints show 15, 25, and 35.

Note

A lambda has no name of its own, so its value name does the calling.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

What does it stand for inside a one parameter lambda?