Scala – Closures

  • Post category:Scala
  • Reading time:3 mins read

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,  pricemethod reference the variable currencyfrom within the showPricemethod 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 currencyvariable (from INRto USD). 

This is Closure functionality. A closure is a block of code which meets three criteria.

  1. The block of code can be passed around as a value, and
  2. It can be executed on demand by anyone who has that value, at which time
  3. 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/