2016-03-15 46 views
1

這裏是迄今爲止我見過的最常規的方法:的建設者,esqe方式添加到一個Groovy列表

threads = [] 
threads << makeAThread("1") 
threads << makeAThread("2") 

但我想做的事:

threads = [] 
threads { 
    << makeAThread("1") 
    << makeAThread("2") 
} 

或者,如果我有到:

threads = [] 
threads { 
    add(makeAThread("1")) 
    add(makeAThread("2")) 
} 

因此,我需要建設者,DSL的建議。

這是我做過什麼(修改,我接受的答案):

threads = [] 
threads.with { 
    add makeAThread("1") 
    add makeAThread("2") 
} 
+1

'高清線= '1', '2']收集{makeAThread它}'但事實並非如此。 builder-esqe的方式;) – dmahapatro

回答

1

可以使用with完成任你的例子。

threads = [] 
threads.with { 
    it << makeAThread("1") 
    it << makeAThread("2") 
} 

threads = [] 
threads.with { 
    add(makeAThread("1")) 
    add(makeAThread("2")) 
} 

with使每一個呼叫或屬性訪問適用於給定對象,在這種情況下threadsleftShift()運營商,<<,需要明確的左側,在這種情況下it

+0

所有的答案都很好(簡短優雅),但我最喜歡這個,因爲它符合我的建設者的理想。不過,我修改了 - 請參閱OP中的最後一個代碼塊。 –

2

爲什麼不是:def threads = [makeAThread("1"), makeAThread("2")]

1

如果@歐泊的解決方案不適合你,你可以鏈<<電話:

threads = [] << makeAThread("1") << makeAThread("2") 
相關問題