簡體   English   中英

Groovy:為什么閉包本身不能訪問?

[英]Groovy: Why can't the closure access itself?

我是Groovy新手。 當我運行以下腳本時,Groovy報告“沒有此類屬性:***類的tailFactorial”。 閉包不應該訪問局部變量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,期待您的幫助。 謝謝。

您不能訪問的變量,以該封閉將被分配到,因為它的右側躍入存在(或至少讓我們不要拍攝)。

這就是為什么第二個示例(與groovy docs中相同的代碼)起作用的原因。 該變量已經聲明,並且閉包可以使用此名稱捕獲它。 (請記住,它沒有立即執行的關閉代碼-在這個確切的時間點tailFactorial將為null)。

但是,由於您僅對閉合處的蹦床調用感興趣,因此可以簡單地在閉合處本身上對其進行調用。 trampoline是一種Closure方法:

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()}"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM