![]() |
VOOZH | about |
According to Kotlin's official documentation "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created. The environment consists of any local variables that were in-scope at the time the closure was created"
var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
}
print(sum)In this example, we will simply create an array of integers and calculate its sum:
Output:
28
In the preceding example, the sum variable is defined in the outer scope; still, we are able to access and modify it.
Closures can also mutate variables they have closed over
Very simply, this code closes over a local variable, containsNegative, setting it to true if a negative value is found in a list. In the real world, you'd use a built-in function for this rather than this function, but it indicates how vars can be updated from inside a function literal.
How to create a closure in Kotlin which takes any type of parameter and gives any type of variable as a return value?
The problem is with test: Int of foo:
val foo = { test: Int -> "Just Testing $test" }
foo requires test to be an Int. If you call foo with a parameter of type Any? it might be null or a type like String. But that would not work. So if you declare it as a test: Any? your code would compile.