thejavajar

{ java, groovy, flex, python, ruby }

Flower

Groovy Closure Currying

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.

Tags: , ,

2 Responses to “Groovy Closure Currying”

  1. April 21st, 2009 at 9:22 pm

    linkfeedr » Blog Archive » Groovy Closure Currying - RSS Indexer (beta) says:

    [...] 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 [...]

  2. May 2nd, 2010 at 5:08 am

    Cartucho Nds says:

    Very interesting topic will bookmark your site to check if you write more about in the future..
    Groovy Closure Currying – thejavajar