Kotlin Closure Tutorial

In this section, we will learn what the closure is and how it works in Kotlin.

Not: we’re assuming you’re already familiar with the Kotlin Lambda Expression.

What is Closure in Kotlin?

When creating a lambda expression and pass that around as the argument to a function, for example, that lambda will remember the place that it was created! We call this as closure!

For example, if in the body of a lambda expression we call a variable that was not defined within the body of the lambda itself, Kotlin will move to the place where the body of the lambda expression was created and then start to look for that variable in the enclosing scopes to get the value of the variable.

Alright, let’s run an example to see how this closure works in Kotlin.

Example: using closure in Kotlin

fun main(){
    var firstName:String = "John"
    var lmd = {println("The firstName is: $firstName")}

    printer(lmd)
}

fun printer(lam:()->Unit){
    var firstName = "Jack"
    lam()
}

Output:

The firstName is: John

How does closure work in Kotlin?

In this example, the lambda expression is created in the body of the main function and is passed as the argument to the printer function.

The body of the lambda expression is simply a call to the println function to print the value of the firstName variable.

But we can see that both functions (main and printer) have this variable as their local members.

Now the question is when the lambda expression is invoked in the body of the printer function, is it going to print the value of the local variable in the printer() function or the one in the main() function?

Well, according to the law of closure, the answer is the value of the firstName variable that was defined in the main() function.

This is because the lambda was defined in the main() function and so our program when want to look for the value of a variable, it will return to the birthplace of the target lambda expression and start to look for the variable in the enclosing scopes there.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies