More Than Five
More Than Five

Reputation: 10429

this, owner, delegate in Groovy closure

Here is my code:

class SpecialMeanings{
  String prop1 = "prop1"
  def closure = {
    String prop1 = "inner_prop1"  
    println this.class.name //Prints the class name
    println this.prop1
    println owner.prop1
    println delegate.prop1
  }
}

def closure = new SpecialMeanings().closure
closure()

output is

prop1
prop1
prop1

I would expect the first line to be prop1 as this refers to the object in which the closure is defined. However, owner (and be default delegate) should refer to the actual closure. So the next two lines should have been inner_prop1. Why weren't they?

Upvotes: 4

Views: 3459

Answers (2)

More Than Five
More Than Five

Reputation: 10429

OK the answer is that by default owner is equal to this and by default delegate is equal to owner. Therefore, by default delegate is equal to this. Unless of course you change the setting of delegate, you therefore get the equivalent value as you would from this

Upvotes: 7

dmahapatro
dmahapatro

Reputation: 50285

This is how it works. You have to understand the actual reference of owner and delegate. :)

class SpecialMeanings{
  String prop1 = "prop1"
  def closure = {
    String prop1 = "inner_prop1"  
    println this.class.name //Prints the class name

    //Refers to SpecialMeanings instance
    println this.prop1 // 1

    // owner indicates Owner of the surrounding closure which is SpecialMeaning
    println owner.prop1 // 2

    // delegate indicates the object on which the closure is invoked 
    // here Delegate of closure is SpecialMeaning
    println delegate.prop1 // 3

    // This is where prop1 from the closure itself in referred
    println prop1 // 4
  }
}

def closure = new SpecialMeanings().closure
closure()

//Example of modifying the delegate to the script itself
prop1 = "PROPERTY FROM SCRIPT"
closure.delegate = this
closure()

Last 3 lines of the scripts shows an example as to how the default delegate can be changed and set to the closure. Last invocation of closure would print the prop1 value from the script which is PROPERTY FROM SCRIPT at println # 3

Upvotes: 12

Related Questions