What is Scala Closure ?
A closure is a function, whose return value depends on the value of one or more variables declared outside this function.Lets say we want to pass a Scala function around like a variable, and while doing so, we want that function to be able to refer to one or more fields that were in the same scope as the function when it was declared.
Example
object MyTest extends App { var currency = "INR" def price(name: String) { println(s" The value of product $name is $currency") } val foo = new otherpackage.Foo foo.showPrice(price, "P1") // Change the local variable "currency". currency = "USD" foo.showPrice(price, "P2") } package otherpackage { class Foo { def showPrice(f: (String) => Unit, name: String) { f(name) } } }
Save the above program in MyTest.scala. The following commands are used to compile and execute this program.
scalac MyTest.scala scala MyTest
Output
The value of product P1 is INR The value of product P2 is USD
So what is your observation ?
If you have noticed, price
method reference the variable currency
from within the showPrice
method of the Foo
class on the first run (NOTE: currency variable is not in scope in showPrice method). On the second run, it picked up the change to the currency
variable (from INR
to USD
).
This is Closure functionality. A closure is a block of code which meets three criteria.
- The block of code can be passed around as a value, and
- It can be executed on demand by anyone who has that value, at which time
- It can refer to variables from the context in which it was created (i.e. it is closed with respect to variable access.
Refrences : https://alvinalexander.com/scala/how-to-use-closures-in-scala-fp-examples/