41

I was reading Object Oriented Javascript and found the concept of closures. I didn't quite understand why and when it is used. Do other languages like Java also have closures? I basically want to understand how knowing the concept of closures can help me improve my coding.

Manoj Govindan
  • 72,339
  • 21
  • 134
  • 141
sushil bharwani
  • 29,685
  • 30
  • 94
  • 128
  • Related: http://stackoverflow.com/questions/795549/difference-between-classjava-and-closurejavascript – Josh Lee Sep 27 '10 at 15:52
  • 1
    If anyone is dumb like me and if you are beating your head against the wall just to know What the hack is this Closure....then here you go.. https://www.youtube.com/watch?v=Nj3_DMUXEbE – Piyush Kukadiya Jan 02 '17 at 07:34

5 Answers5

37

A closure is a first class function with bound variables.

Roughly that means that:

  • You can pass the closure as a parameter to other functions
  • The closure stores the value of some variables from the lexical scope that existed at the time that is was created

Java initially didn't have syntactic support for closures (these were introduced in Java 8), although it was fairly common practice to simulate them using anonymous inner classes. Here's an example:

import java.util.Arrays;
import java.util.Comparator;

public class StupidComparator { 
    public static void main(String[] args) {
        // this is a value used (bound) by the inner class
        // note that it needs to be "final"
        final int numberToCompareTo=10;

        // this is an inner class that acts like a closure and uses one bound value
        Comparator<Integer> comp=new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                int result=0;
                if (a<numberToCompareTo) result=result-1;
                if (b<numberToCompareTo) result=result+1;
                return result;
            }
        };

        Integer[] array=new Integer[] {1,10, 5 , 15, 6 , 20, 21, 3, 7};

        // this is a function call that takes the inner class "closure" as a parameter
        Arrays.sort(array,comp);

        for (int i:array) System.out.println(i);
    }
}
mikera
  • 105,238
  • 25
  • 256
  • 415
  • Thanks mikera, what i know understand is clousure is a function with some variables that can be passed as parameters to other functions. I have two questions wat is a first class function and what do you mean by stores some values from lexical scope. Also i am still not getting a perfect scenario where i would be benifited by using it. Sorry i am very new to it so asking too much – sushil bharwani Sep 27 '10 at 16:23
  • 3
    First class function means that you can treat the function just as you would any other "object" in the language, i.e. pass it as a parameter, store it in a collection etc. Since an anonymous inner class represents a Java object just like any other object, it is "first class" in Java - you can do anything to it that you could do with any other normal object – mikera Sep 27 '10 at 16:44
  • 1
    Example of the benefit is given above - you have a generic sorting function (e.g. Arrays.sort(..)) that becomes much more powerful because you can pass any comparison function you like a parameter. e.g. you could sort in reverse order, or by number of digits, or by whether or not the number is a prime etc. This basically gives you an extra layer of abstraction when creating algorithms that can be very powerful. It's worth reading up on "functional programming" if you want to learn more. – mikera Sep 27 '10 at 16:47
  • wow .. wonderful explanation... – sushil bharwani Sep 27 '10 at 16:57
  • Here is a closure implementation for Java 5, 6, and 7 http://mseifed.blogspot.se/2012/09/closure-implementation-for-java-5-6-and.html It contains all one could ask for... – mjs Sep 29 '12 at 20:53
  • What's the difference between a closure and a "simulated" closure, then? If we're already dealing with abstract concepts, does it really matter what's original and what's simulated? A claim that they are substantially different should demonstrate what's possible with "real" closures that isn't possible in Java's implementation. – DavidS Mar 16 '16 at 20:31
  • 2
    @DavidS I'd say the difference is between a closure that is naturally supported in the language syntax vs. finding another way to achieve the same effect (which is ultimately possible in any Turing-complete language). As of Java 8, Java does in fact have pretty decent syntactic support for closures, introduced as part of the Lambda expression support. – mikera Mar 18 '16 at 10:54
  • @mikera as far as I understand, the concept of a closure only has to do with nested lexical scopes, rather than functions specifically -- hence Java has had closures in nested class scopes for a long time. – Andy Apr 21 '17 at 16:08
  • @mikera a closure has greater capabilities than a lambda, in that with a closure you would expect to be able to modify the variable where-as with a lambda the variable becomes final, this makes it impossible to use lambdas to update outer scope. So I would disagree that lambdas provide good closure support, although I do very much like lambdas but that's another matter. – Quaternion Apr 15 '20 at 20:41
  • So, is it means closure is the same thing as what we call delegate, Lambada or anonymous function in C++. C#, JavaScript, Java, Delphi (Pascal)? Is that a PhD level name for something we BSc levels use on daily basis? – AaA Apr 25 '21 at 03:59
15

Closures are know by various names in various languages but the essential points are as follows:

To create closures you need a language where the function type is a 1st class citizen i.e. it can be bound to a variable and passed around like any old string, int or bool.

You also need to be able to declare functions inline. In javascript you can do something like this:

foo("bar", "baz" function(x){alert("x")});

To pass a anonymous function as a parameter to the foo function. We can use this to create a closure.

Closures "close over" variables so can be used to pass scoped variables around. Consider this example:

function foo(){
    var spam = " and eggs";
    return function(food){alert(food + spam)};
}
var sideOfEggs = foo();

The side of eggs now contains a function which appends " and eggs" to whatever foodstuff it is passed. The spam variable is part of the foo function scope and would have been lost when the function exited, except that the closure "closed over" the namespace preserving it as long as the closure remains in memory.

So we're clear on closures having access to their parent's private scoped variables right? So how about using them to simulate private access modifiers in javascript?

var module = (function() {   
    var constant = "I can not be changed";

     return {
         getConstant    :    function() {  //This is the closure
            return constant;               //We're exposing an otherwise hidden variable here
         }
    };
}());                                     //note the function is being defined then called straight away

module.getConstant();                     //returns "I can not be changed"
module.constant = "I change you!";
module.getConstant();                     //still returns "I can not be changed" 

So what's happening here is we're creating and immediately calling an anonymous function. There is one private variable in the function. It returns an object with a single method which references this variable. Once the function has exited the getConstant method is the sole way of accessing the variable. Even if this method is removed or replaced it will not give up it's secret. We have used closures to achieve encapsulation and variable hiding. For a more thorough explanation of this see http://javascript.crockford.com/private.html

Java does not have closures (yet). The closest it has are anonymous inner classes. However to instantiate one of these inline you have to instantiate an entire object (usually from an existing interface).The beauty of closures is they encapsulate simple, expressive statements which is somewhat lost in the noise of anonymous inner classes.

Ollie Edwards
  • 14,042
  • 7
  • 28
  • 36
  • From Wikipedia: "The term closure is often mistakenly used to mean anonymous function. This is probably because most languages implementing anonymous functions allow them to form closures and programmers are usually introduced to both concepts at the same time. These are, however, distinct concepts." – Kirk Woll Sep 27 '10 at 15:57
  • @Kirk Woll fair point although it was not my intention to equate the two as identical. I will try to make that a bit clearer. – Ollie Edwards Sep 27 '10 at 16:08
  • i like your explanation.Can you give a more practical example where it makes perfect sense as to yes using the closure was the perfect way to solve a problem – sushil bharwani Sep 27 '10 at 17:04
  • @sushil bharwani sure, see my new section on using closures to simulate private members in javascript – Ollie Edwards Sep 28 '10 at 09:40
  • Even though you are right about scope of `constant` variable, I don't think `module.constant` is the same as `var constant` inside the function. What you are doing is adding another constant to module as property. you can verify that by reading `module.constant` again, which will still return `"I change you!"` – AaA Apr 25 '21 at 03:56
11

While Java doesn't have first-class functions, it does in fact have lexical closures.

For instance, the following Lisp function (stolen from Paul Graham's book On Lisp) returns a function that adds a number:

(defun make-adder (n)
  (lambda (x) (+ x n))

This can be done in Java. However, since it doesn't have first-class functions, we need to define an interface (let's call it Adder) and an anonymous inner class with a function that implements this interface.

public interface Adder {
    int add(int x);
}

public static Adder makeAdder(final int n) {
    return new Adder() {
        public int add(int x) {
            return x + n;
        }
    };
}

The inner add() function is a lexical closure because it uses the n variable from the outer lexical scope.

The variable had to be declared final in order to do this, which means that the variable cannot change. However, changing values within reference variables is possible, even if they are final. For instance, consider the following Lisp function (also from On Lisp):

(defun make-adderb (n)
  (lambda (x &optional change)
    (if change
        (setq n x)
        (+ n n))))

This can be implemented in Java by wrapping the outer variable in a reference type variable, such as an array or object.

public interface MutableAdder {
    int add(int x, boolean change);
}

public static MutableAdder makeAdderB(int n) {
    final int[] intHolder = new int[] { n };
    return new MutableAdder() {
        public int add(int x, boolean change) {
            if (change) {
                intHolder[0] = x;
                return x;
            }
            else {
                return intHolder[0] + x;
            }
        }
    };
}

I will claim that this is real lexical closures, not a simulation. But I won't claim that it's pretty.

Soulman
  • 2,910
  • 24
  • 21
4

A closure is a scoping technique. Java does not have closures.

In javascript you can do something like that following:

var scope = this;

var f = function() {
    scope.somethingOnScope //scope is 'closed in' 
}

if you then do something like pass f to a function, scope is the scope of where it was defined.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
  • What would you call it then when you refer to variables declared outside the scope of your anonymous class? – Kirk Woll Sep 27 '10 at 15:52
  • I have read it that the closure is a scoping technique. Thanks but i want to understand how it helps with a particular coding scenario. – sushil bharwani Sep 27 '10 at 15:54
  • @sushil its useful because it allows you to associate a scope with something (e.g. a function) and then pass that function around. – hvgotcodes Sep 27 '10 at 16:00
3

Closure is a very natural feature that allows free-variables to be captured by their lexical environment.

here's an example in javascript:

function x() {

    var y = "apple";

    return (function() {
         return y;
    });
}

function x returns a function. note that when a function is created variables used in this function are not evaluated like when we return an expression. when the function is created it looks to see what variables are not local to the function (free). It then locates these free variables and ensures they are not garbage collected so that they can be used once the function is actually called.

In order to support this feature you need to have first-class functions which java does not support.

Note this is a way we can have private variables in languages like JavaScript.

John Topley
  • 113,588
  • 46
  • 195
  • 237
Ken Struys
  • 1,789
  • 1
  • 10
  • 17
  • 3
    FSVO "very natural". The very question points out that it's arcane to many. – Adriano Varoli Piazza Sep 27 '10 at 15:58
  • there are applications where it's really natural. forexample when passing around callback functions, and when you're working in functional languages. Just because it's arcane doesn't mean it's not a good idea. :P – Ken Struys Sep 27 '10 at 16:00
  • Oh, I don't question their usefulness, far from it. Just saying that it did take some time to wrap my head around them, for me. – Adriano Varoli Piazza Sep 27 '10 at 16:07
  • When you have to explain what's going on and you've programmed in imperative languages for a very long time it can be hard. I've seen novice functional programmers just use them without thinking about it and think "we'll of course that will work". – Ken Struys Sep 27 '10 at 16:23
  • I do like the terminology "allows free-variables to be captured by their lexical environment." – Tim Aug 23 '16 at 19:36