SoFunction
Updated on 2025-04-06

How Kotlin captures variables and constants in context detailed explanation

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): () -&gt; List&lt;String&gt; {
  //Create a List that does not contain any elements  var list: MutableList&lt;String&gt; = mutableListOf()
  fun addElement(): List&lt;String&gt; {
   //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&lt;String&gt;) {
 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.