This posting展示了如何遍历Scala中的玫瑰树。我想做类似的事情:在玫瑰树中的每个CNode
上调用一个方法。以下是CNode
定义:
case class CNode(
name: String,
helpMessage: String = "",
children: List = Nil,
alias: String = ""
)
以下是方法定义:
def node(objects: AnyRef*): SomeReturnValue
以下是一些测试数据:
val cNodes = List(
CNode("account",
helpMessage = "Account management", children = List(
CNode("import", children = List(CNode("<keyfile>"))),
CNode("list", helpMessage = "List accounts"),
CNode("new", helpMessage = "Create a new account"),
CNode("update", children = List(CNode("<accountAddress>")))
)
),
CNode("javascript"),
CNode("help")
)
所以,我想要完成的是将上面的List[CNode]
转换为这样的递归调用结构:
val result = List(
node("account", children = List(
node("import", children = List(node("<keyfile>"))),
node("list"),
node("new"),
node("update", children = List(node("<accountAddress>")))
),
node("javascript"),
node("help")
)
答案 0 :(得分:0)
骑自行车回家我意识到有一种解决问题的简单方法:
implicit def cNodeToNode(cNode: CNode): Node =
node(cNode.name :: cNode.children.cNodes.map(cNodeToNode).toList: _*)