Groovy delegates working as intended?

纵然是瞬间 提交于 2020-01-14 16:54:25

问题


I have a short snippet where I try to delegate the variable resolution to the delegate. However the delegates value isnt used, instead the owners value is used. Is this intentional or is this a bug?

class Person {
    int age
}

def age = -5
def closure = { -> age }
closure.delegate = new Person(age: 99)
closure.resolveStrategy == Closure.DELEGATE_ONLY

assert closure.call() == 99

Above code fails, with the closure returning -5.


回答1:


Your code returns -5 because the variable age is defined withing the lexical scope of the closure, meaning that the closure can use the value of the variable age.

You have to explicitly tell the closure to use the age property of the delegate:

def closure = { -> delegate.age }

Try the following code:

class Person {
    int age
}  
def age = -5 
def closure = { -> delegate.age * age } 
closure.delegate = new Person(age: 99)
closure.resolveStrategy == Closure.DELEGATE_ONLY 
assert closure.call() == 99*-5


来源:https://stackoverflow.com/questions/32368483/groovy-delegates-working-as-intended

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