在groovy中是否已经有一种方法来收集属性后的对象而不是null?
Object.metaClass {
collectWhileNotNull = { Closure follow ->
def result = []
def previous = null
for (def current = delegate; !current.is(previous) && (current != null); current = follow(current)){
result << current
previous = current
}
return result
}
}
它对递归数据结构非常有用。
groovy.util.Node的使用示例:
Closure getAncestors = { Node n -> n.collectWhileNotNull{ it.parent() }.tail().reverse() }