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() }