Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 174 ]

In addition to the this keyword, Groovy has two other keywords that are referred
only in the context of a closure—owner and delegate:



  • The owner keyword refers to the enclosing object, which in the majority
    of cases is the same as this, the only exception being when a closure is
    surrounded by another closure.

  • The delegate keyword refers to the enclosing object and is usually the same
    as owner except that delegate is assignable to another object. Closures relay
    method invocations that they handle themselves back to their delegate
    keywords. This is how the methods of an enclosing class become available to
    be called by the closure as if the closure was also an instance method. We will
    see later that one of the reasons builders work the way they do is because
    they are able to assign the delegate of a closure to themselves.


The delegate keyword will initially default to owner,
except when we explicitly change the delegate keyword to
something else through the Closure.setDelegate method.

The following example illustrates this, owner, and delegate working under various
different contexts. This example is necessarily complex, so take the time to read and
understand it:


class Clazz {
def method() {
this
}

def methodDelegate() {
delegate
}

def methodOwner() {
owner
}
def closure = {
[this, delegate, owner]
}

def closureWithinMethod() {
def methodClosure = {
[this, delegate, owner]
}
methodClosure()

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