Fundamentals 3 min read

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.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Understanding Closures in Scala

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 = 6
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

programmingfundamentalsclosureScalafunctional
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.