Lambdas and Higher-Order Functions
Capturing Variables
Let a lambda use a value from the surrounding scope.
Capturing Variables
CapturingVariables.kt
fun applyToBase(base: Int, change: (Int) -> Int): Int {
val updated = change(base)
return updated
}
fun main() {
val offset =
val result = applyToBase(10) { value ->
value + offset
}
println("offset=$offset")
println("result=$result")
}
fun applyToBase(base: Int, change: (Int) -> Int): Int {
val updated = change(base)
return updated
}
fun main() {
val offset =
val result = applyToBase(10) { value ->
value + offset
}
println("offset=$offset")
println("result=$result")
}
fun applyToBase(base: Int, change: (Int) -> Int): Int {
val updated = change(base)
return updated
}
fun main() {
val offset =
val result = applyToBase(10) { value ->
value + offset
}
println("offset=$offset")
println("result=$result")
}
capture
A lambda can read nearby variables without receiving them as parameters.