Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 104 ]

We can continue currying parameters until we run out of parameters (or curry
powder). At this point, we have a curried closure lambKormaBoiled that can be
invoked without passing any parameters:


when: "we exhaust all the parameters"
def lambKormaBoiled = lambKorma.curry "Boiled"
then:
lambKormaBoiled() == "Lamb Korma with Boiled rice."
lambKormaBoiled() == lambKorma("Boiled")
lambKormaBoiled() == korma("Lamb","Boiled")
lambKormaBoiled() == indian("Korma","Lamb","Boiled")

Curried closures can be used very effectively in circumstances where contextual data
needs to be gathered on the fly and then acted upon. We can write an appropriate
closure that acts on all parameters as if they were available. We curry the parameters
of the closure as we discover them, and eventually invoke the closure to act on the
data. The only limitation that we have is that our closure parameters need to be
defined in the correct order.


Since the release of Groovy 1.8, we are no longer limited to currying parameters from
left to right. Two new closure methods are available to curry right to left and to curry
any arbitrary nth parameter:


when: "we curry the closure with right parameters"
def fried = indian.rcurry "Fried"
then:
fried "Vindaloo","Chicken" == "Chicken Vindaloo with Fried rice."

when: "we curry the closure with 2nd parameters"
def chicken = indian.ncurry 1, "Fried"
then:
chicken "Vindaloo","Fried" == "Chicken Vindaloo with Fried rice."

Closure return values


Closure declarations syntax provides no means of defining a return value. Every
closure does, however, return a value with each invocation. A closure can have
explicit return statements. If a return statement is encountered, then the value
defined in the return statement is returned; otherwise, execution continues until
the last statement in the closure block:


given: "a closure that returns values"
def closure = { param ->
if (param == 1)
return 1

http://www.ebook3000.com
Free download pdf