this, owner, delegate in Groovy closure

筅森魡賤 提交于 2019-12-23 17:56:56

问题


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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/23449376/this-owner-delegate-in-groovy-closure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!