admin管理员组

文章数量:1122846

Learning about lambdas and I encountered this "...the lifetime of a local variable is constrained by the function in which the variable is declared. But if it's captured by the lambda, the code that uses this variable can be stored and executed later." The text offers no code example of this process. Is there a code example that does what is being claimed?

Learning about lambdas and I encountered this "...the lifetime of a local variable is constrained by the function in which the variable is declared. But if it's captured by the lambda, the code that uses this variable can be stored and executed later." The text offers no code example of this process. Is there a code example that does what is being claimed?

Share Improve this question asked yesterday Ken KiarieKen Kiarie 291 silver badge6 bronze badges 2
  • Where did you read that? – Sweeper Commented yesterday
  • "Kotlin in Action" book – Ken Kiarie Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 5

Normally, local variables cease to exist once the function that declared them returns.

fun someFunction() {
    var x = 0
    // "x" ceases to exist after someFunction returns
}

Let's capture x into a lambda:

fun someFunction(): () -> Unit {
    var x = 0
    // here "x" is captured
    val someLambda = { println(x++) }
    x = 10
    return someLambda
}

x's lifetime has been extended to be as long as the lambda. To show this, I made someFunction return the lambda so that it can be used even after someFunction returns. Let's call the lambda a few times in main.

fun main() {
    val f = someFunction()
    f() // prints 10
    f() // prints 11
    f() // prints 12
}

Clearly, f is still printing the value of x and incrementing it, even after someFunction has returned. This shows that x still exists after someFunction has returned.

The idea is that once a variable is captured in a lambda, that lambda can be passed around to other things, and it can be called long after the original function that declared the variable has returned. The variable's lifetime must be extended, or else who knows will happen when those lambdas are called?

本文标签: kotlinCapturing a local variableStack Overflow