How kotlin captures variables and constants in context
Lambda expressions or anonymous functions can access or modify variables and constants in their context. This process is called capture.
fun main(args: Array<String>) {
//定义一个函数,该函数的返回值类型为()->List<String>
fun makeList(ele: String): () -> List<String> {
//创建一个不包含任何元素的List
var list: MutableList<String> = mutableListOf()
fun addElement(): List<String> {
//向list集合中添加一个元素
list.add(ele)
return list
}
return ::addElement
}
}
In the above example, a local function can access or modify the variables in its function.
Lambda expressions or anonymous functions will hold a copy of the variables they capture, so on the surface, addelement() accesses the list collection variables of makelist() function, but as long as the program returns a new addelement() function, addelement() function will hold a new copy of list.
Lambda expressions or anonymous functions will hold a copy of the variables they capture. Therefore, on the surface, addelement() accesses the list collection variables of makelist() function. 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返回的List**********")
val add1 = makeList("刘备")
println(add1())
println(add1())
println("******add2返回的List**********")
val add2 = makeList("关羽")
println(add2())
println(add2())
}
Output results:
summary
The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. Thank you for your support.
