Saturday, 10 January 2015

Closure in Scala


In computer science, a closure (also lexical closure or function closure) is a function together with a referencing environment for the non-local variables of that function. A closure allows a function to access variables outside its immediate lexical scope.

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.
For example:

package otherscope {

  class Foo {
    def exec(f:(String) => Unit, name: String) {
      f(name)
    }
  }

}

object ClosureExample extends App {

  var hello = "Hello"
  def sayHello(name: String) { println(s"$hello, $name") }

  // execute sayHello from the exec method foo
  val foo = new otherscope.Foo
  foo.exec(sayHello, "Al")

  // change the local variable 'hello', then execute sayHello from
  // the exec method of foo, and see what happens
  hello = "Hola"
  foo.exec(sayHello, "Lorenzo")

}



"hello" is not a formal parameter; it’s a reference to a variable in the enclosing scope (similar to the way a method in a Java class can refer to a field in the same class). Therefore, the Scala compiler creates a closure that encompasses (or “closes over”) hello.

To create a closure in Scala, just define a function that refers to a variable that’s in the same scope as its declaration. That function can be used later, even when the variable is no longer in the function’s current scope, such as when the function is passed to another class, method, or function.

No comments:

Post a Comment