这是迄今为止我见过的最常见的方式:
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")
}
答案 0 :(得分:2)
为什么不:def threads = [makeAThread("1"), makeAThread("2")]
?
答案 1 :(得分:1)
您可以使用with
完成任一示例。
threads = []
threads.with {
it << makeAThread("1")
it << makeAThread("2")
}
或
threads = []
threads.with {
add(makeAThread("1"))
add(makeAThread("2"))
}
with
使每个调用或属性访问都适用于给定对象,在本例中为threads
。 leftShift()
运算符<<
需要明确的左侧,在本例中为it
。
答案 2 :(得分:1)
如果@ Opal的解决方案不适合您,您可以链接<<
来电:
threads = [] << makeAThread("1") << makeAThread("2")