def tryClosures(code, nbr, text) {
1.upto(nbr) {
code.call(text)
}
}
tryClosures({println(it.toUpperCase())}, 3, "Greg")That's a nice trick but what is the benefit?
First, a look at the code to store a string of text without the use of closures.
def file = new File("filetouse.txt")
def stream = new FileOutputStream( file );
stream.write( "store this string\n".getBytes() );
stream.close();
Now, let's see the better alternative. It uses the static use() method in Resource which accepts a closure passed to it. Note that repetitious housekeeping is eliminated from this code, leaving 'DRY', declarative code which more clearly shows intent.
Resource.use { it ->
it.write("so groovy\n")
}
class Resource {
FileOutputStream file;
Resource() {
file = new FileOutputStream( new File("sogroovy.txt"), true )
}
def static use(closure) {
def r = new Resource()
try {
closure(r)
}
finally {
r.close()
}
}
def void close() {
file.close()
}
def write(String s) {
file.write(s.getBytes())
}
}