Closures

 

A lambda expression, anonymous function, local function and an object expression can access its closure. The variables declared in the outer scope.

 

Let's take a look at the following example (Closures.kt):

 

fun tryClosures() {

val values = listOf<Int>(2, 4, 6, 8, 10)

var result = 0

values.forEach {

result += it

}

println("Result: $result")

}

 

Console output:

 

Result: 30