Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 328
More Than Five Avatar asked Dec 03 '22 19:12

More Than Five


1 Answers

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

like image 117
dmahapatro Avatar answered Mar 08 '23 07:03

dmahapatro