Understanding Closures in Scala
This article explains the concept of closures, showing how a function can capture external variables, illustrated with Scala examples that demonstrate anonymous functions, free variables, and a complete runnable program producing expected output.
Closure is a function whose return value depends on one or more variables declared outside the function.
In simple terms, a closure can be regarded as another function that can access the local variables of a function.
For example, the following anonymous function: val multiplier = (i:Int) => i * 10 The function body contains a variable i as a parameter. Another example: val multiplier = (i:Int) => i * factor In multiplier there are two variables: i and factor. i is a formal parameter receiving a new value on each call, while factor is a free variable defined outside the function: var factor = 3<br/>val multiplier = (i:Int) => i * factor Here we introduce a free variable factor that is defined outside the function.
Thus the function variable multiplier becomes a "closure" because it references the externally defined variable, capturing it to form a closed function.
Complete example:
object Test {<br/> def main(args: Array[String]) {<br/> println( "muliplier(1) value = " + multiplier(1) )<br/> println( "muliplier(2) value = " + multiplier(2) )<br/> }<br/> var factor = 3<br/> val multiplier = (i:Int) => i * factor<br/>}Running the above code produces the following output:
$ scalac Test.scala<br/>$ scala Test<br/>muliplier(1) value = 3<br/>muliplier(2) value = 6Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
