Open In App

Closures in Kotlin

Last Updated : 07 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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)
  • Closures in functional programming are the functions that are aware of their surroundings By this, I mean that a closure function has access to the variables and parameters defined in the outer scope.
  • Remember that in Java and traditional procedural programming, the variables were tied to the scope, and as soon as the block got executed, local properties were blown out of the memory.
  • Java 8 lambdas can access outer variables, but can’t modify them, and this limits the capabilities if you try to do functional programming in Java 8.
  • Let’s take a look at an example where we work with closures in Kotlin.

Example

In this example, we will simply create an array of integers and calculate its sum:

Kotlin




fun main (args: Array<String>) {
  sum=0
  var listOfInteger= arrayOf (0, 1, 2, 3, 4, 5, 6, 7)
  listOfInteger.forEach {
    sum+=it
    println (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

Kotlin




var containsNegative = false
val ints = listOf(0, 1, 2, 3, 4, 5)
ints.forEach {
  if (it < 0)
  containsNegative = true
}


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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads