在我们当前的应用程序中,我们需要遍历树并捕获特定设备(和子设备)上的所有操作员。设备可以具有子设备,并且子设备上还具有特定的操作员。
由于我对 Groovy 中的递归使用不熟悉,我想知道我做的事情是否正确..?有什么建议可以帮助我学习更好的做事方法吗?
def listOperators(device) {
// list with all operator id's
def results = []
// closure to traverse down the tree
def getAllOperators = { aDevice->
if(aDevice) {
aDevice.operators.each { it ->
results << it.id
}
}
if (aDevice?.children) {
aDevice.children.each { child ->
results << owner.call(child)
}
}
}
// call the closure with the given device
getAllOperators(device)
// return list with unique results
return results.unique()
}
Run Code Online (Sandbox Code Playgroud)
有几点需要注意:
进行递归调用owner并不是一个好主意。owner如果调用嵌套在另一个闭包中,则定义会发生变化。它很容易出错,并且与仅使用名称相比没有任何优势。当闭包是局部变量时,将其声明和定义分开,以便名称位于范围内。例如:
def getAllOperators
getAllOperators = { ...
您将运算符附加到递归闭包外部的结果列表中。但是您还将每个递归调用的结果附加到同一个列表中。要么追加到列表中,要么存储每个递归调用的结果,但不能同时执行两者。
这是一个更简单的替代方案:
def listOperators(device) {
def results = []
if (device) {
results += device.operators*.id
device.children?.each { child ->
results += listOperators(child)
}
}
results.unique()
}
Run Code Online (Sandbox Code Playgroud)