Wednesday, September 09, 2009

Closures in Java... and other languages

Recently I've been exchanging emails with some friends about closures, high-order functions (HOFs) and Java blocks.

These appear to be very popular topics at the time, so here are some pointers/info ;)

- Martin Fowler wrote a nice article about collections and closures: here.

A typical use of HOFs is the map function (following a LISP tradition). The map takes a list and another function as input, and applies the function to all elements of the list.
In Javascript it could be implemented like this:

function map(f, arr) {
var r = [];
for (i=0;i< arr.length;i++) { r[i] = f(arr[i]); }
return r;

function f(x) { return x + 100; }

map( f , [ 1, 2, 3 ]);

And the result will be: [ 101, 102, 103 ]

To implement this in Java one should have pointers to methods, which are not supported, so usually the effect is replicated by a design pattern (strategy for example).

An example of closure in Javascript instead:

function someCounter(initialValue, increment){
var v = initialValue;
var inc = increment;

return function(){
return v += inc;

var c1 = someCounter(0,1);
var c2 = someCounter(10,-1);

document.write( "c1 => " + c1() + " , c2 => " + c2() +"<br>");
document.write( "c1 => " + c1() + " , c2 => " + c2() +"<br>");
document.write( "c1 => " + c1() + " , c2 => " + c2() +"<br>");

Blocks are a Smalltalk concept (see here)
The definition of blocks in Smalltalk is:
"Each block is an object. More precisely we can say that every block
is represented by an object which is created at run-time and which can
be stored in variables, like any other object. "

Which also means that in Smalltalk a closure IS an object!

No comments:

Post a Comment