Skip to content

M0112: Owning value in an escaping lambda ​

error

What it means ​

A lambda that is not inlined and is not a thread boundary (a closure object) captures an owning value. The closure object retains what it captures and may outlive it. Closures as owners (move capture) are not supported yet.

Minimal failing example ​

From the test corpus: compiler/testdata/memory/capture_escaping_lambda.kt. The corpus expects 13:12: M0112 (the ^ comment in the source marks the column).

kotlin
// REJECT M0112: an owned value captured by a lambda that escapes. Spec 5.5, 7.12
@file:MemoryMode(Mode.Strict)

package memory.capture_escaping_lambda

import mini.memory.*

class Box(val v: Int)

context(h: Heap)
fun later(): () -> Int {
    val b = Box(3)
    return { b.v }
//         ^ M0112
}

fun main() {
    context(Heap()) { println(later()()) }
}

Compiler output ​

Generated by running ./minic check compiler/testdata/memory/capture_escaping_lambda.kt (exit status 1).

text
$ ./minic check compiler/testdata/memory/capture_escaping_lambda.kt
error[M0112]: owned `b` is captured by a closure that escapes
  --> compiler/testdata/memory/capture_escaping_lambda.kt:13:12   the closure borrows `b` and is returned
   13 |     return { b.v }
      |            ^
  help: keep the closure inside the function (call it or pass it to a function that does not keep it), make the called function `inline`, pass `b` as a parameter, or read what you need before creating the closure

note: M0112 (Owning value in an escaping lambda): https://henryschwerdt.github.io/mini/reference/diagnostics/M0112

error: could not compile capture_escaping_lambda.kt (1 error, 0 warnings)

How to fix ​

Make the called function inline (inline lambdas are read like code at the call), pass the value to the code that needs it as an explicit parameter, or read the data you need (b.v) before creating the lambda and capture that instead.

Corpus programs for this code ​

See also: Diagnostics overview and the memory guide.

Released under the Apache License 2.0.