在列表闭包中获取 "calling" 列表大小

Getting "calling" list size in list closure

我需要在 Groovy 列表闭包中获取 "calling" 列表大小,例如:

def foo = [1,2,3,4,5]
def bar = foo.findAll {
   someCondition(it)
}.collect {
   processElement(it, <self>.size())
}

其中 <self> 是使用 findAll.

过滤 foo 的结果列表

当然可以把中间结果保存起来,得到它的大小,但是没有它行吗?

我目前能想到的最好的是:

def bar = foo.findAll { someCondition(it) }
             .with { list ->
                 list.collect { processElement(it, list.size()) }
             }

但这只是使用 with 而不是中间结果。

或者,您可以使用闭包的委托:

def foo = [1,2,3,4,5]
def collector = { it -> processElement(it, delegate.size()) }

(collector.delegate = foo.findAll { someCondition(it) }).collect collector

但这只是使用委托作为中间结果;-)