From: Greg McIntyre Date: 2005-09-07T10:46:29+09:00 Subject: Re: ruby style blocks in java On Wed, 07 Sep 2005 02:36:28 +1000, Martin Ankerl wrote: > 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 > } > } > From my experience attempting exactly the same, that's as close as I could get too (using final 1-element arrays to write back to the block's calling context). I also ran across Groovy. There's also jruby but I haven't really tried either. I also found it better to stick the interface inside the class that uses it and name it after the method that uses it. Exception handling can also be a PITA with this kind of thing. Despite being verbose, the sort of thing you have above actually cut down the number of lines of Java code I had to write by factoring out a whole lot of JDBC try/finally code. If you hunt around for the recommended way of using JDBC you'll see there are about 6 lines inside a finally clause that involve cleaning up the record set and statement objects. The main problem I found though is that all those Java standard libraries simply don't use blocks, so they're only good for things you implement yourself. -- Greg McIntyre