Scala - Closures

A closure is a function whose return value depends on one or more variables declared outside of the function.

A closure is usually thought of as another function that can access a local variable in a function.

An anonymous function like this:

val multiplier = (i:Int) => i * 10  

The function body has a variable i, which is a parameter of the function. Another piece of code like the following:

val multiplier = (i:Int) => i * factor

There are two variables in multiplier: i and factor. One of them is a formal parameter of the function, and i is given a new value when the multiplier function is called. However, factor is not a formal parameter, but a free variable, consider the following code:

var factor = 3  
val multiplier = (i:Int) => i * factor  

Here we introduce a free variable factor, which is defined outside the function.

The function variable multiplier thus defined becomes a "closure" because it refers to a variable defined outside the function. The process of defining this function captures the free variable to form a closed function.

Full instance

object Test {  
   def main(args: Array[String]) {  
      println( "muliplier(1) value = " +  multiplier(1) )  
      println( "muliplier(2) value = " +  multiplier(2) )  
   var factor = 3  
   val multiplier = (i:Int) => i * factor  

Execute the above code, the output is:

$ scalac Test.scala  
$  scala Test  
muliplier(1) value = 3  
muliplier(2) value = 6