English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
A closure is a function whose return value depends on one or more variables declared outside the function.
In general, a closure can be simply understood as another function that can access the local variables of a function.
As follows, this anonymous function:
val multiplier = (i: Int) => i * 10
There is a variable i in the function body, which is a parameter of the function. As shown in the following code snippet:
val multiplier = (i: Int) => i * factor
There are two variables in multiplier: i and factor. One of them, i, is a formal parameter of the function, which is assigned 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 defined in this way becomes a "closure" because it refers to variables defined outside the function. The process of defining this function is to capture the free variable and 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 }
Executing the above code, the output is:
$ scalac Test.scala $ scala Test muliplier(1) value = 3 muliplier(2) value = 6