Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Created December 10, 2012 16:03
Show Gist options
  • Save anoopelias/4251484 to your computer and use it in GitHub Desktop.
Save anoopelias/4251484 to your computer and use it in GitHub Desktop.
Closure..

Closure..

Couple of months back, when I started looking at Scala as a programming language, a key computer programming concept came up - Closure. I couldn't find a page which explains what it is and how to use it, so here it goes,

Definition

A closure is a first-class function with free variables that are bound in the lexical environment. (Source wikipedia)

First-class functions

First-class functions are those that can be assigned to a variable to be carried around and be executed at a later point of time. Subsequently this will enable those functions being passed as arguments, as well as returned back. An example in Scala is shown below.

object Square {

  def main(args: Array[String]) = {
    val square = (
      (x: Int) =>
      {
        x * x
      })

    var num = 1;
    println(square(num)); // Prints 1

    num += 1;
    println(square(num)); // Prints 4

    num += 1;
    println(square(num)); // Prints 9

    num += 1;
    println(square(num)); // Prints 16
  }
}

The 'square' variable in this example holds a first-class function. This function takes an integer x as the argument and returns its square. The subsequent println statements use this function to calculate the square of a number.

Closure

A 'Closure' is a first class function, but will have some additional variable values bound along with it. Well, that makes 'Closure' a function with a state!

These variables are those which are available to access around where the function is defined. An example such as below might make this more clear.

object SquareClosure {

  def createNextSq() : () => Int = {
    var x = 0;
    val nextSquare = 
    { ()  =>
      {
        x = x + 1
        x * x
      }
    }
    return nextSquare;
  }

  def main(args: Array[String]) = {
    var nextSquare = createNextSq()

    println(nextSquare()); // Prints 1
    println(nextSquare()); // Prints 4
    println(nextSquare()); // Prints 9
    println(nextSquare()); // Prints 16

    nextSquare = createNextSq()
    println(nextSquare()); // Start all over again, prints 1
  }
}

The nextSquare function created in createNextSq method is an example of a Closure. When createNextSq method returns the first-class nextSquare function, it will initialise variable x with zero and sends it along with. Every time nextSquare is called, the value of x is incremented. As the variable x is bound to the closure, this value is kept intact till the next call, though it is accessible only through the call.

So, to say this again, Closure is simply a function with a state!

Closure and OO

You can consider Closure as an object which has only one public method, and the state managed as private variables inside. If you stand in that restriction, Closure would be a more elegant implementation than its OO counterpart because of its lesser lines of code and more readability.

Though Closure as such is not supported in Java(TM), it is possible to achieve this behaviour using inner classes. How to do that is outside the scope of this discussion, and may be worthy of another post.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment