views:

343

answers:

1

Hi,

The following example is adapted from 'Groovy in Action'

class Mother {

    Closure birth() {                            
        def closure = { caller ->
            [this, caller]
        }
        return closure
    }
}                    

Mother julia = new Mother()
closure = julia.birth()                                
context = closure.call(this)                             

println context[0].class.name        // Will print the name of the Script class
assert context[1] instanceof Script

According to the book, the value of this inside the closure is the outermost scope (i.e. the scope in which julia is declared). Am I right in assuming that

  • this inside a closure evaluates to the scope in which the closure is called?
  • within the closure shown above, this and caller refer to the same scope?

Thanks, Don

+4  A: 

Take a look at page 144

...this refers to the closure, not to the declaring object. At this point, closures play a trick for us. They delegate all method calls to a so-called delegate object, which by default happends to be the declaring object (that is, the owner). This make the closure appear as if the enclosed code runs in the birthday context.

For your questions;

this inside a closure evaluates to the scope in which the closure is called?

Be aware that this is the closure not the object where the closure constructed. "this.XXX" delegate the evaluation to the the scope in which the closure is constructed by default.

within the closure shown above, this and caller refer to the same scope?

I'm afraid not.

Be aware that page 143 and 144 in Groovy in Action need some corrections

http://groovy.canoo.com/errata/erratum/show/5

http://groovy.canoo.com/errata/erratum/show/8

Sake