Thursday, August 13, 2009

Groovy Closure vs. javascript closure

Coming from a javascript and java background, i've learned to use the javascript closure to its full advantage, but when we used groovy (on grails) for our new system, I was surprise that the concept of closure in groovy is different.

The definition of closure in groovy (from groovy.codehaus.org) is that, a groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. It has some special properties like implicit variables, support for currying and support for free variables (which we'll see later on). We'll ignore the nitty gritty details for now (see the formal definition if you want those) and look at some simple examples.

GROOVY CODE:

def myclosure = { println "hello world!" }

println "Executing the Closure:"
myclosure() //prints "hello world!"



The javascript closure is a functionality that marks a variable, that it will be use later. So even when it goes out of scope, the data is saved in the memory. Here's an example:



function SayHelloTo(name) {
var greeting = 'Hello ' + name;
var display = function() { alert(greeting); }
return display;
}

var greet = new SayHelloTo("Aidan Thor");
greet();




This is simply defining a method with a local variable called "greeting" and another method inside called display, then it returns that method.

When you instantiate "SayHelloTo", and execute it ( "greet()"), you would think that it will throw an error, because "greeting" is out of scope, but actually it will not throw an error, because the method created a closure (knowing that "greeting" will be called later).

3 comments:

Unknown said...

Your JavaScript example works in Groovy as well.

def sayHelloTo(name) {
def greeting = 'Hello ' + name
def display = { println greeting }
return display
}

def greet = sayHelloTo("Aidan Thor")
greet()

liminescence said...

Thanks! I guess for all dynamic languages they concepts are the same. I wouldn't be surprise if it will yield similar result with ruby and python.

unknown said...

rlovtang: Groovy closures can have lexical scoping. But the terms 'closure' is not the same between Groovy and JavaScript. In JavaScript, when we mean a closure, we mean that the variables are closed over and can be accessed even after the main function returns. Where as in Groovy, a closure is a name given to a block of code.