Within a Groovy Closure, several variables are defined that have special meaning:
it
If you have a Closure that takes a single argument, you may omit the parameter definition of the Closure, like so:
def clos = { print it } clos( "hi there" ) //prints "hi there"
this
, owner
, and delegate
this
: as in Java, this
refers to the instance of the enclosing class where a Closure is defined
owner
: the enclosing object (this or a surrounding Closure)
delegate
: by default the same as owner, but changeable for example in a builder or ExpandoMetaClass
Example:
~/Lgroovy/closures$ cat -n ThisDelegate.groovy 1 def clos = new Class1().closure 2 clos.delegate = this 3 clos() 4 5 class Class1 { 6 def closure = { 7 println "Inside closure" 8 println "this = "+this 9 println "this.class.name = "+this.class.name 10 println "delegate = "+delegate 11 println "delegate.class.name = "+delegate.class.name 12 println "owner = "+owner 13 println "owner.class.name = "+owner.class.name 14 15 def nestedClos = { 16 println " Inside nestedClos" 17 println " this = "+this 18 println " delegate = "+delegate 19 println " owner.class.name = "+owner.class.name 20 } 21 22 nestedClos() 23 } 24 } ~/Lgroovy/closures$ groovy ThisDelegate.groovy Inside closure this = Class1@57d840cd this.class.name = Class1 delegate = ThisDelegate@5d04e28b delegate.class.name = ThisDelegate owner = Class1@57d840cd owner.class.name = Class1 Inside nestedClos this = Class1@57d840cd delegate = Class1$_closure1@78ff9053 owner.class.name = Class1$_closure1
Casiano Rodríguez León