Scala Closures
A closure is a function whose return value depends on one or more variables declared outside the function.
Generally speaking, a closure can be simply considered as another function that can access the local variables of a function.
For example, the following anonymous function:
val multiplier = (i:Int) => i * 10
There is a variable i inside the function body, which serves as a parameter of the function. As for the following code:
val multiplier = (i:Int) => i * factor
In the multiplier, there are two variables: i and factor. One of them, i, is a formal parameter of the function, and when the multiplier function is called, i is assigned a new value. 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 defined in this way becomes a "closure" because it references a variable defined outside the function, and the process of defining this function is to capture this free variable and form a closed function.
Complete Example
Example
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
}
When the above code is executed, the output is:
$ scalac Test.scala
$ scala Test
muliplier(1) value = 3
muliplier(2) value = 6