Scala closures
Scala Function
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 thought of as another function that can access local variables in a function.
For example, the following anonymous function:
val multiplier = (i:Int) => i * 10
There is a variable i in the function body, which is used as a parameter of the function. As another piece of code below:
val multiplier = (i:Int) => i * factor
There are two variables in the multiplier: i and factor. One of i is a formal parameter of the function. 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 refers to a variable defined outside the function. The process of defining this function is to capture this free variable to form a closed function.
Complete 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 }
Execute the above code, the output result is:
$ scalac Test.scala $ scala Test muliplier(1) value = 3 muliplier(2) value = 6