簡體   English   中英

常規閉包實例化變量

[英]groovy closure instantiate variables

有可能使用閉包從值列表中創建一組變量嗎? 要求這樣做的原因是基於(例如)兩個,三個,四個或五個部分的列表創建一些遞歸功能。這里的代碼當然不起作用,但是任何指針都會有所幫助。

def longthing = 'A for B with C in D on E'
//eg shopping for 30 mins with Fiona in Birmingham on Friday at 15:00
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']

i = 0
line = place = with = event = ""
breaks.each{
shortline = longthing.split(breaks[i])
longthing= shortline[0]
//this is the line which obviously will not work
${vary[i]} = shortline[1]
rez[i] = shortline[1]
i++
 }
return place + "; " + with + "; " + event
// looking for answer of D; C; B

編輯>>

是的,我正在嘗試找到一種更簡潔的方法來清理此問題,每個循環之后我都必須這樣做

len = rez[3].trim()
if(len.contains("all")){
len = "all"
} else if (len.contains(" ")){
len = len.substring(0, len.indexOf(" ")+2 )
}
len = len.replaceAll(" ", "")
with = rez[2].trim()
place = rez[1].trim()
when = rez[0].trim()
event = shortline[0]

如果我決定將另一個項目添加到列表中(我剛剛做了),我必須記住要成功提取出哪個[i]

這是工作部件,用於解析日期/時間,然后使用jChronic將自然文本轉換為公歷日歷信息,因此我可以在Google日歷中設置事件

怎么樣:

def longthing = 'A for B with C in D on E'
def breaks = [" on ", " in ", "with ", " for "]
def vary = ['when', 'place', 'with', 'event']
rez = []
line = place = with = event = ""

breaks.eachWithIndex{ b, i ->
  shortline = longthing.split(b)
  longthing = shortline[0]
  this[vary[i]] = shortline[1]
  rez[i] = shortline[1]
}
return place + "; " + with + "; " + event

當使用帶有List和“ each”的閉包時,groovy循環遍歷List中的元素,將列表中的值放在“ it”變量中。 但是,由於您還想跟蹤索引,因此在索引中還傳遞了一個俗套的eachWithIndex

http://groovy.codehaus.org/GDK+Extensions+to+Object

所以像

breaks.eachWithIndex {item, index ->
   ... code here ...
}

暫無
暫無

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

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