簡體   English   中英

Groovy:如何獲得“私有”的價值? 封閉變量

[英]Groovy: how to get the value of a ?private? closure variable

我的閉包效果很好,但是有時我想獲得在閉包中定義的臨時變量的最終值。 例:

def someClosure = {Number input->
  def howDoIGetThis = input + 4
  return 2 * input
}

def normalWay = someClosure(2)
assert normalWay == 4

def myFantasy = someClosure(2).howDoIGetThis
assert myFantasy == 6

這可能嗎?

您可以將狀態存儲在閉包的所有者或委托中。

def howDoIGetThis
def someClosure = {Number input ->
    howDoIGetThis = input + 4
    return input * 2
}

def normalWay = someClosure(2)
assert normalWay == 4

someClosure(2)
def myFantasy = howDoIGetThis
assert myFantasy == 6

如果要控制狀態進入的對象,則可以覆蓋閉包的委托。 例如:

def closureState = [:]
def someClosure = {Number input ->
    delegate.howDoIGetThis = input + 4
    return input * 2
}
someClosure.delegate = closureState

def normalWay = someClosure(2)
assert normalWay == 4

someClosure(2)
def myFantasy = closureState.howDoIGetThis
assert myFantasy == 6

不,沒有辦法獲取變量,因為閉包僅返回一個結果(因此somclosure(2).howDoIGetThis不能工作),並且在閉包實例運行后也無法獲取句柄。 ..

我能想到的最好的辦法是從Closure返回多個值,如下所示:

def someClosure = {Number input->
  def howDoIGetThis = input + 4
  [ 2 * input, howDoIGetThis ]
}

def (normalWay, myFantasy) = someClosure(2)

assert normalWay == 4
assert myFantasy == 6

暫無
暫無

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

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