我有一个action
我需要在object
多次执行,并使用该对象收集每个action
的结果。
基本上看起来像这样
def one_action = { obj ->
def eval_object = process(obj)
eval_object.processed = true
return eval_object
}
def multiple_actions = { obj, n, action ->
def result = []
n.times {
result << action(obj)
}
return result
}
println multiple_actions(object, 10, one_action)
有没有办法省略def result = []
的声明并直接从闭包中返回列表?
答案 0 :(得分:3)
您可以collect
范围,从零开始:
def one_action = { obj ->
"a $obj"
}
def multiple_actions = { obj, n, action ->
(0..<n).collect { action obj }
}
assert multiple_actions("b", 3, one_action) == ["a b"] * 3