Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Groovy Closures


[ 108 ]

The this, owner, and delegate variables


Groovy has three implicit variables in scope inside each closure. They are: this,
owner, and delegate. The this variable refers to the enclosing class, providing that
one exists. If the closure is defined within the scope of a script, the enclosing class is
the script class. This will be autogenerated if we are running in the GroovyConsole
or the Groovy shell.


The owner variable is the enclosing object of the closure. This is generally analogous
to this, except in the case of nested closures where the enclosing object is another
closure. The delegate variable is also usually the same as the owner variable, except
that delegate can be changed.


In most closures, we only need to care about this as a means of accessing field
variables in an outer scope. The owner and delegate variables will only become
relevant later in the book when we deal with implementing our own builders.


Closure composition


In mathematics, we can compose a new function from other functions. Suppose we
have a function f: R -> R given by f(x) = 2x + 4 and another function g: R -> R given
by g(x) = x^3. We can compose a new function fg: R -> R given by fg(x) = 2x^3 + 4 or the
reverse composition gf: R -> R given by gf(x) = (2x + 4)^3 :


Therefore:



  • fg(x) = f(g(x)) = f(x^3 ) = 2x^3 + 4

  • gf(x) = g(f(x)) = g(2x + 4) = (2x + 4)^3


In Groovy, we can compose a new closure from two existing closures using <<
for composition and >> for reverse composition. So we can mimic the preceding
functions in two closures, and compose them using Groovy closure composition.


This can be expressed with Groovy closures as follows:


given: "two closures for f(x) = 2x + 4 and g(x) = x cubed"
def f = { it*2 + 4}
def g = {it * it * it}
and: "a closure composed from these"
def fg = f << g
and: "a reverse composition of the same"
def gf = f >> g
expect:
fg(10) == f(g(10))

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