Scala Tutorial Scala Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Scala - Closures



Scala Closure is a function which uses one or more free variables and the return value of the function depends on the value of these variables. A free variable is any kind of variable which is not defined within the function and not passed as the parameter of the function.

Consider the following block of code:

val TotalSum = (x:Int) => 10 + x

Above is an anonymous function. Here, only one variable x is used, which is defined as a parameter of the function. Now consider the following block of code:

val TotalSum = (x:Int) => k + x

Here, two variables k and x are used. The variable x is the parameter of the function. However, the variable k is a free variable because it is neither defined within the function nor passed as the parameter of the function. The above function is a closure function.

Depending on the type of the free variable, a closure function can further be classified into pure and impure functions. If the free variable is declared as type var, its value can change any time throughout the entire code and hence the value of the closure function can also change. This type of closure function is a impure function. If the free variable is declared as type val, its value will remain constant. This type of closure function is a pure function.

Example:

Consider the example below, where closure function is used to add two numbers. Here, free variable is defined as type val.

object MainObject {
  def main(args: Array[String]) {
    val k = 10
    def TotalSum = (x:Int) => k + x

    println("TotalSum(10) = " + TotalSum(10)) 
    println("TotalSum(25) = " + TotalSum(25)) 
    println("TotalSum(50) = " + TotalSum(50)) 
  }
}

The output of the above code will be:

TotalSum(10) = 20
TotalSum(25) = 35
TotalSum(50) = 60

Example:

Here, free variable is defined as type var and its value can change throughout the entire code. Consider the example below:

object MainObject {
  def main(args: Array[String]) {
    var bonus = 2000
    val EmployeeBonus = (name: String) => 
      println(s"$name got a bonus amount of $bonus dollars.")

    EmployeeBonus("John")
    EmployeeBonus("Marry")
    EmployeeBonus("Kim")

    //changing free variable
    bonus = 1800

    EmployeeBonus("Jo")
    EmployeeBonus("Suresh")
    EmployeeBonus("Peter")
  }
}

The output of the above code will be:

John got a bonus amount of 2000 dollars.
Marry got a bonus amount of 2000 dollars.
Kim got a bonus amount of 2000 dollars.
Jo got a bonus amount of 1800 dollars.
Suresh got a bonus amount of 1800 dollars.
Peter got a bonus amount of 1800 dollars.

5