Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1
Chapter 5

[ 111 ]

trampolined.trampoline(n - 1, n * accumulator)
}.trampoline()
and: "we memoize() the trampolined closure"
def factorial = trampolined.memoize()
expect: "it still correctly calculates factorials"
factorial(1) == 1
factorial(3) == 1*2*3
factorial(6) == 1*2*3*4*5*6

Summary


In this chapter, we covered closures in some depth. We covered all of the important
aspects of working with closures. We explored the various ways to call a closure and
the means of passing parameters. We saw how we can pass closures as parameters to
methods, and how this construct can allow us to appear to add mini DSL syntax to
our code.


Closures are the real "power" feature of Groovy, and they form the basis of most
of the DSLs that we will develop later in this book. In the next chapter, we will
build on this knowledge of closures and take a look at some more of the power
features of the Groovy language, including builders and metaprogramming with
the ExpandoMetaClass classes.

Free download pdf