Explanation of how Kotlin captures variables and constants in context
- 2021-11-10 10:55:08
- OfStack
Lambda expressions or anonymous functions can access or modify variables and constants in their context, a process known as capture.
fun main(args: Array<String>) {
// Definition 1 Function with a return value type of ()->List<String>
fun makeList(ele: String): () -> List<String> {
// Create 1 Object that contains no elements List
var list: MutableList<String> = mutableListOf()
fun addElement(): List<String> {
// Toward list Add to the collection 1 Elements
list.add(ele)
return list
}
return ::addElement
}
}
In the above example, the top one has one local function, which can access or modify the variables in its function.
Lambda expressions or anonymous functions hold a copy of the variables they capture, so apparently addElement () accesses the list set variables of makeList (), but addElement () holds a copy of the new list whenever the program returns a new addElement () function.
Lambda expression or anonymous function will hold a copy of the variables it captures, so on the surface, addElement () accesses list set variables of makeList () function, and as long as the program returns a new addElement () function, it will hold a new copy of list.
fun main(args: Array<String>) {
println("******add1 Returned List**********")
val add1 = makeList(" Liu Bei ")
println(add1())
println(add1())
println("******add2 Returned List**********")
val add2 = makeList(" Guan Yu ")
println(add2())
println(add2())
}
Output:
********* List********** returned by add1
[Liu Bei]
[Liu Bei, Liu Bei]
********List********** add2 Returned List*****
[Guan Yu]
[Guan Yu, Guan Yu]
Summarize