Pass a short lambda expression to a helper function.

lambda A lambda is a compact block of code that can be passed as a value.

Lambda Basics

value
LambdaBasics.kt
Replay: real traced execution (multi-file project)
fun transform(value: Int, action: (Int) -> Int): Int {
    val result = action(value)
    return result
}

fun main() {
    val value = 4
    val doubled = transform(value, { number ->
        number * 2
    })

    println("value=$value")
    println("doubled=$doubled")
}
fun transform(value: Int, action: (Int) -> Int): Int {
    val result = action(value)
    return result
}

fun main() {
    val value = 2
    val doubled = transform(value, { number ->
        number * 2
    })

    println("value=$value")
    println("doubled=$doubled")
}
fun transform(value: Int, action: (Int) -> Int): Int {
    val result = action(value)
    return result
}

fun main() {
    val value = 7
    val doubled = transform(value, { number ->
        number * 2
    })

    println("value=$value")
    println("doubled=$doubled")
}
  1. value ← 4

    6fun main() {7    val value→ 4 = 4 //@value=2, 78    val doubled = transform(value4, { number ->9        number * 210    })
  2. result ← 8

    1fun transform(value4: Int, action: (Int) -> Int): Int {2    val result→ 8 = action(value4)3    return result84}
  3. doubled ← 8

    7    val value = 4 //@value=2, 78    val doubled→ 8 = transform(value4, { number ->9        number * 210    })1112    println("value=$value4")13    println("doubled=$doubled8")14}
    outputvalue=4
    doubled=8
  1. value ← 2

    6fun main() {7    val value→ 2 = 28    val doubled = transform(value2, { number ->9        number * 210    })
  2. result ← 4

    1fun transform(value2: Int, action: (Int) -> Int): Int {2    val result→ 4 = action(value2)3    return result44}
  3. doubled ← 4

    7    val value = 28    val doubled→ 4 = transform(value2, { number ->9        number * 210    })1112    println("value=$value2")13    println("doubled=$doubled4")14}
    outputvalue=2
    doubled=4
  1. value ← 7

    6fun main() {7    val value→ 7 = 78    val doubled = transform(value7, { number ->9        number * 210    })
  2. result ← 14

    1fun transform(value7: Int, action: (Int) -> Int): Int {2    val result→ 14 = action(value7)3    return result144}
  3. doubled ← 14

    7    val value = 78    val doubled→ 14 = transform(value7, { number ->9        number * 210    })1112    println("value=$value7")13    println("doubled=$doubled14")14}
    outputvalue=7
    doubled=14