gpt4 book ai didi

Groovy:为什么闭包不能访问自身?

转载 作者:行者123 更新时间:2023-12-02 04:21:13 24 4
gpt4 key购买 nike

我是 Groovy 新手。当我运行以下脚本时,Groovy 报告“No such property: tailFactorial for class ***”。闭包不应该访问局部变量 tailFactorial 吗?

def factorial(int factorialFor) {
def tailFactorial = { int number, BigInteger theFactorial = 1 ->
number == 1 ? theFactorial :
tailFactorial.trampoline(number - 1, number * theFactorial)
}.trampoline()
tailFactorial(factorialFor)
}
println "factorial of 5 is ${factorial(5)}"
println "Number of bits in the result is ${factorial(5000).bitCount()}"

让我困惑的是,如果我将上面的代码更改为以下代码:

def factorial(int factorialFor) {
def tailFactorial
tailFactorial = { int number, BigInteger theFactorial = 1 ->
number == 1 ? theFactorial :
tailFactorial.trampoline(number - 1, number * theFactorial)
}.trampoline()
tailFactorial(factorialFor)
}
println "factorial of 5 is ${factorial(5)}"
println "Number of bits in the result is ${factorial(5000).bitCount()}"

运行良好。

我们可以发现,这两段代码之间的唯一区别是,在第一段代码中,我们同时声明和定义了闭包,而在第二段代码中,我们声明了闭包,但没有定义。定义位于单独的行中。

怎么会发生这种事?我正在使用 Groovy 2.4.3 和 Java 7,期待您的帮助。谢谢。

最佳答案

您无法访问闭包将分配给的变量,因为它在右侧之后弹出(或者至少没有捕获 get )。

这就是第二个示例(与 groovy 文档中的代码相同)有效的原因。该变量已被声明,并且闭包可以通过该名称捕获它。 (请记住,闭包代码不会立即执行 - 在这个确切的时间点 tailFactorial 将为 null)。

但是由于您只对闭包上的蹦床调用感兴趣,因此您可以简单地在闭包本身上调用它。 trampolineClosure 的一种方法:

def factorial(int factorialFor) {
def tailFactorial = { int number, BigInteger theFactorial = 1 ->
number == 1 ? theFactorial :
// XXX
trampoline(number - 1, number * theFactorial)
}.trampoline()
tailFactorial(factorialFor)
}
println "factorial of 5 is ${factorial(5)}"
println "Number of bits in the result is ${factorial(5000).bitCount()}"

关于Groovy:为什么闭包不能访问自身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30316313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com