M
Martin Ankerl
Is there a nice way to implement Ruby-style blocks in Java? I have to
code in Java and I really miss this feature. This is the best thing I
came up with, but it is soooo verbose (untested, just from my head):
interface Block {
public Object yield(Object o);
}
class Array {
public void do(Block b) {
// do something here
while (it.hasNext()) {
Object o = it.next();
block.yield(o);
}
}
class Someth
public void doSomething() {
Array a = new Array();
// do something before
a.do(new Block() {
public void yield(Object o) {
// here is the yield code
}
}
// do something afterwards
}
}
code in Java and I really miss this feature. This is the best thing I
came up with, but it is soooo verbose (untested, just from my head):
interface Block {
public Object yield(Object o);
}
class Array {
public void do(Block b) {
// do something here
while (it.hasNext()) {
Object o = it.next();
block.yield(o);
}
}
class Someth
public void doSomething() {
Array a = new Array();
// do something before
a.do(new Block() {
public void yield(Object o) {
// here is the yield code
}
}
// do something afterwards
}
}