Groovy Closure Currying
by RJ Salicco on Feb.09, 2009, under Development
So I have been diving into Groovy a bit heavier lately and I was just checking out Closure currying. So let’s say I have a Closure, like myClosure below, that takes in 2 parameters, var1 and var2. Let’s look at the code:
...
def myClosure = { var1, var2 ->
var1.call()
var2.call()
}
def walk = { println "I am walking..." }
def run = { println "I am running..." }
def fly = { println "I am flying..." }
myClosure(walk, run)
myClosure(walk, fly)
def walkFirst = myClosure.curry(walk)
walkFirst(run)
walkFirst(fly)
...
When I call myClosure(walk, run) and myClosure(walk, fly) I get:
... I am walking... I am running... I am walking... I am flying... ...
Well what curry() does for us is take out some of the duplication that we may find when passing in parameters to our Closure. I notice that the Closure walk is passed in both times because we want to walk before we can run or fly. If we take advantage of curry() we can create another Closure called walkFirst. The Closure, walkFirst, is created here:
... def walkFirst = myClosure.curry(walk) ...
This now gives us a simpler Closure we can send run and fly into without worrying about having to pass in walk first. This is a very useful utility of Groovy and Closures and we get exactly what we were expecting:
... I am walking... I am running... I am walking... I am flying... ...
Very cool stuff. Do yourself a favor, read more about Groovy.

1 Trackback or Pingback for this entry
April 21st, 2009 on 9:22 pm
[...] Currying VA:F [1.1.7_509]please wait…Rating: 0.0/5 (0 votes cast) This article was found on . Click here to visit the full article on the original website.So I have been diving into Groovy a bit heavier lately and I was just checking out Closure [...]