Blocks in Java (an implementation)
I have been thinking more about blocks recently, and how they would look in Java. I’ve come up with an implementation that uses inner classes and is is fairly straightforward.
It would be quite easy to implement this as a source transformation in a Java compiler, in much the same way that C# does with delegates and function pointers (which are also actually implemented as inner classes)
The full description and implementation is on my wiki at http://skizz.plus.com/mywiki/BlocksInJava
Essentially, a block like
//Ideal syntax
public block void foreach(Object obj) {
for ( int i=0; i<size(); i++ ) {
yield(get(i));
}
}
could be implemented in Java as:
public Block foreachBlock = new Block() {
public void run(BlockCaller caller) {
for (int i = 0; i < size(); i++) {
Object[] values = new Object[] { get(i) };
if ( caller.yield( values ) == BlockCaller.BREAK )
return;
}
}
};
The block is used as follows:
//Ideal syntax
list.foreach( Object item ) {
System.out.println(item);
}
implemented in Java as:
list.foreachBlock.run(
new BlockCaller() {
public int yield(Object[] args) {
Object item = args[0];
System.out.println(item);
return CONTINUE;
}
}
);