簡體   English   中英

在groovy中構建閉包時,是否可以引用變量的值,而不是變量本身?

[英]Is it possible reference the value of a variable when building a closure in groovy, rather than the variable itself?

我明白為什么

x = 'foo'
closure={print x}
x = 'bar'
closure() 

將返回“ bar”,因為閉包中的變量將始終引用變量的當前值。 但是我想做的是動態地構建一個閉包{print'foo'},以便當我調用閉包時,它總是根據構建閉包時發生的x總是輸出相同的內容。 那可能嗎?

您可以使用方法添加一個間接級別,因此閉包將關閉方法參數而不是外部變量

def close(x) {
    { -> println x }
}

x = 1
closure = close(x)
x = 2
closure()

或者,您可以通過(可能不太容易理解)雙閉包調用來做到這一點:

x = 1
closure = { x -> { -> println x } }(x)
x = 2
closure()

您可以使用curry()

def x = 'foo'
def closure = { it }.curry(x)

x = 'bar'
assert closure() == 'foo'

暫無
暫無

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

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