Search code examples
scalatheoryclosuresdefinition

What is a full powered closure?


I was at a Java conference on Scala the other day and the speaker referred to 'full powered closures'. I am having a hard time nailing down a definition that makes sense to me. I have read the wiki page on closures but it really didn't answer it for me. Can someone help me with a clear cut definition? Maybe even include a simple example.

Thanks!


Solution

  • In computer science, a closure is a first-class function with free variables that are bound in the lexical environment.

    You don't need more than this sentence from the wikipedia article. What Java lacks (in addition to the ugly syntax) is the feature of binding free variables from outside the closure. An example:

    int x = 0;
    new Runnable() {
        public void run() {
            x = 1;
        }
    }.run();
    

    Here the Java compiler will complain about the variable x.

    The same thing in scala works just fine and is a lot less verbose:

    var x = 0
    val fun = ()=>{x=1}
    fun