Java and Closures
Posted on August 26, 2006
Gilad Bracha, Neal Gafter, James Gosling and Peter von der Ahé wrote a proposal on closures for Java language.
some code that is quite awkward to express in Java (particulary when it comes to GUI programming):
public interface Runnable {
void run();
}
public interface API {
void doRun(Runnable runnable);
}
public class Client {
void doit(API api) {
api.doRun(new Runnable(){
public void run() {
snippetOfCode();
}
});
}
}
Can be expressed quite terse and elegantly using closures:
public interface API {
void doRun(void() func);
}
And the client like this:
public class Client {
void doit(API api) {
api.doRun( () {
snippetOfCode();
});
}
and as side benefit closures can access all class variables. The only negative aspect that authors mention is the fact that Java API was designed around interfaces and anonymous classes and can’t be changed to make full use of closures.
There are other ways to solve this problem. For example there exist an RFE for shorter syntax for common operations.
Filed Under Uncategorized |
Leave a Comment
If you would like to make a comment, please fill out the form below.
Read the whole proposal and subsequent posts. Closures integrate beautifully with existing code based on interfaces.