Lambdas and Higher-Order Functions
Capturing Variables
Let a lambda use a value from the surrounding scope.
capture
A lambda can read nearby variables without receiving them as parameters.
Capturing Variables
CapturingVariables.kt
Replay: real traced execution (multi-file project)
fun applyToBase(base: Int, change: (Int) -> Int): Int {
val updated = change(base)
return updated
}
fun main() {
val offset = 2
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 = 0
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 = 5
val result = applyToBase(10) { value ->
value + offset
}
println("offset=$offset")
println("result=$result")
}
offset ← 2
6fun main() {7 val offset→ 2 = 2 //@offset=0, 58 val result = applyToBase(10) { value ->9 value + offset10 }updated ← 12
1fun applyToBase(base10: Int, change: (Int) -> Int): Int {2 val updated→ 12 = change(base10)3 return updated124}result ← 12
7 val offset = 2 //@offset=0, 58 val result→ 12 = applyToBase(10) { value ->9 value + offset10 }1112 println("offset=$offset2")13 println("result=$result12")14}outputoffset=2 result=12
offset ← 0
6fun main() {7 val offset→ 0 = 08 val result = applyToBase(10) { value ->9 value + offset10 }updated ← 10
1fun applyToBase(base10: Int, change: (Int) -> Int): Int {2 val updated→ 10 = change(base10)3 return updated104}result ← 10
7 val offset = 08 val result→ 10 = applyToBase(10) { value ->9 value + offset10 }1112 println("offset=$offset0")13 println("result=$result10")14}outputoffset=0 result=10
offset ← 5
6fun main() {7 val offset→ 5 = 58 val result = applyToBase(10) { value ->9 value + offset10 }updated ← 15
1fun applyToBase(base10: Int, change: (Int) -> Int): Int {2 val updated→ 15 = change(base10)3 return updated154}result ← 15
7 val offset = 58 val result→ 15 = applyToBase(10) { value ->9 value + offset10 }1112 println("offset=$offset5")13 println("result=$result15")14}outputoffset=5 result=15