Lambda expressions or anonymous functions can access or modify variables and constants in their context, and this process is called capture.
fun main(args: Array<String>) { //Define a function whose return value type is ()->List<String> fun makeList(ele: String): () -> List<String> { //Create a List that does not contain any elements var list: MutableList<String> = mutableListOf() fun addElement(): List<String> { //Add an element to the list collection (ele) return list } return ::addElement } }
In the above example, the local function can access or modify the variables in the function it is located.
Lambda expressions or anonymous functions will hold a copy of the variable it captures. Therefore, on the surface, addElement() accesses the list collection variable of the makeList() function, but as long as the program returns a new addElement() function, the addElement() function will hold a new copy of the list.
Lambda expressions or anonymous functions will hold a copy of the variable it captures. Therefore, on the surface, addElement() accesses the list collection variable of the makeList() function. As long as the program returns a new addElement() function, it will hold a copy of the new list.
fun main(args: Array<String>) { println("*********Returned by ****************") val add1 = makeList("Liu Bei") println(add1()) println(add1()) println("*********Returned by ****************") val add2 = makeList("Guan Yu") println(add2()) println(add2()) }
Output result:
**********Returned by add1*************
[Liu Bei]
[Liu Bei, Liu Bei]
*******Returned List************
[Guan Yu]
[Guan Yu, Guan Yu]
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support.