Groovy代表按预期工作? [英] Groovy delegates working as intended?
问题描述
我有一个简短的代码片段,我尝试将可变分辨率委托给委托人。然而代理人的价值没有被使用,而是使用所有者的价值。这是故意的还是这个bug?
class Person {
int age
}
def age = -5
def closure = { - >年龄}
closure.delegate = new Person(年龄:99)
closure.resolveStrategy == Closure.DELEGATE_ONLY
断言closure.call()== 99
以上代码失败,返回-5。
你的代码返回 -5
,因为变量 age
是用关闭的词汇范围,这意味着关闭可以使用变量 age
的值。
您必须明确地告诉闭包使用委托的age属性:
def closure = { - >
$ / 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
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.
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
这篇关于Groovy代表按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!