Question

In the last example of this page (http://groovy.codehaus.org/JN3525-MetaClasses), the closure code to override the metaClass invokeMethod call refers to a "delegate". Code is also copied below:

class Bird{
  def name= 'Tweety'
  def twirp(){ 'i taught i saw a puddy cat' }
}
Bird.metaClass.invokeMethod= {name, args->
  def metaMethod= Bird.metaClass.getMetaMethod(name, args) 
        //'getMetaMethod' gets method, which may be an added or an existing one
  metaMethod? metaMethod.invoke(delegate,args): 'no such method'
}
def a= new Bird()
assert a.twirp() == 'i taught i saw a puddy cat'
assert a.bleet() == 'no such method'

Bird.metaClass.getProperty= {name->
  def metaProperty= Bird.metaClass.getMetaProperty(name) 
    //'getMetaProperty' gets property, which may be an added or an existing one
  metaProperty? metaProperty.getProperty(delegate): 'no such property'
}
def b= new Bird()
assert b.name == 'Tweety'
assert b.filling == 'no such property'

Where exactly is the delegate coming from and two what does it refer to?

It seems to refer to the Bird class, but how does this fit into Groovy closures and the implementation of the language as a whole?

Was it helpful?

Solution

It seems to refer to the Bird class, but how does this fit into Groovy closures and the implementation of the language as a whole?

To answer the above, it does refer to instance of Bird. It acts similar to this operator but outside the context of the wrapped object denoted by this. This can be explained with a small example:

Integer.metaClass.sayHello = {
    return "Say hello $delegate times"
}

assert 2.sayHello() == "Say hello 2 times" 
assert 20.sayHello() == "Say hello 20 times" 


Integer.metaClass.sayHi = {
    return "Say hello $this times"
}

println 2.sayHi()

Mark at the last println if you are running in Groovy Console. this operator represents the script on which you run the above code.

In addition to the above explanation, do visit the links provided in my comment.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top