7. Lambdas and captures
How a lambda is treated depends on whether it can outlive the code around it.
| Kind of lambda | Treatment |
|---|---|
Inline: passed to an inline function, not crossinline/noinline (use, repeat, run, let, forEach, context(x) { }, ...) | transparent: the checker reads the body as if it were written at that place |
Thread lambda: a parameter marked @ThreadBoundary (like spawn) | captured owners move in; the lambda runs once and owns them |
| Everything else (escaping) | may not capture owned values, see below |
Inline lambdas are transparent
kotlin
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
context(h: Heap)
fun run() {
repeat(2) { i -> // inline lambda: the checker reads the body like ordinary code
val b = Box(i)
println(b.v)
b.free()
}
val c = Box(9)
run {
println(c.v)
c.free() // freeing an outer owner inside an inline lambda is fine
}
}
fun main() {
context(Heap()) { run() }
}Owners may be freed or moved inside the block, and locals created inside are checked like any other code. The checker accepts the program.
Escaping lambdas
kotlin
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
context(h: Heap)
fun later(): () -> Int {
val b = Box(3)
return { b.v } // the lambda escapes and would have to own `b`
}
fun main() {
context(Heap()) { println(later()()) }
}A closure that captures an owned object borrows it: it may be called, held in a local and passed to functions that do not keep it, as long as it does not outlive the owner. Using it after the owner was freed is M0101; letting it escape (returning it, storing it in a field, passing it to a function that keeps it) is rejected with M0112. Read the data you need before creating the lambda and capture that, or pass the value as a parameter.
Further rules for escaping lambdas:
- capturing a borrowed value is M0109 (the loan would outlive its lender),
- capturing an arena object in a lambda that leaves the arena's scope is M0105,
- capturing an untracked value (a primitive, a Managed object) is always allowed,
- a lambda that is only called locally may capture arena objects and loans.
Next: Threads and ThreadSafe.