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
1 Answer
Reset to default 5Normally, 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
版权声明:本文标题:kotlin - Capturing a local variable - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736283266a1926913.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论