The best Scala closure Tutorial In 2024, In this tutorial you can learn Scala closure
Closure is a function that returns a value dependent on the external declaration in a function or more variables.
Closures Generally considered to be simply another function inside a function can access the local variables.
This anonymous function as the following:
val multiplier = (i:Int) => i * 10
Function body has a variable i, as a function parameter. Another piece of code like the following:
val multiplier = (i:Int) => i * factor
There are two variables in the multiplier: i and factor. Where i is a formal parameter of the function, the function is called when the multiplier, i was given a new value. However, factor is not the formal parameters, but the free variables, consider the following codes:
var factor = 3 val multiplier = (i:Int) => i * factor
Here we introduce a free variable factor, this variable is defined outside of the function.
Multiplier function variables thus defined as a "closure", because it refers to a variable outside the function definition, the definition of the process of this function is to capture the free variables constitute 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 }
Implementation of the above code, the output is:
$ scalac Test.scala $ scala Test muliplier(1) value = 3 muliplier(2) value = 6