只要递归调用的返回类型是 Any,下面的代码就会编译,但显然我做错了,因为它不应该是 Any。
case class Group(
id: Long = -1,
parentId: Long = -1,
name: String = "")
def makeTree(groupId: Long, groups: List[Group]) = {
def getAllChildren(gid: Long): Any = {
def children = for {
g <- groups; if g.parentId == gid
} yield g
if (children.isEmpty) List()
else {
children map { x =>
getAllChildren(x.id)
}
}
}
getAllChildren(groupId)
}
val groups = List(Group(1, 0, "A"),
Group(2, 1, "B"),
Group(3, 1, "C"),
Group(4, 2, "D"))
makeTree(1, groups)
//Results in: Any = List(List(List()), List())
}
如果我将 getAllChildren 的签名更改为:
def getAllChildren(gid: Long): List[Group]
然后我得到一个错误:
type mismatch; found : List[List[Group]] required: List[Group]
我在这里做错了什么。