多次重复动作并收集结果

时间:2016-02-10 17:47:52

标签: groovy

我有一个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 = []的声明并直接从闭包中返回列表?

1 个答案:

答案 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