只要遞歸調用的返回類型是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]
我在做什麼錯在這裏。
謝謝Ingo的好解釋。我現在看到爲什麼我總是得到空列表。 Chirlo的例子確實會返回內容,但不幸的是,flatMap會導致父子關係的結構丟失。我正在嘗試構建一棵樹。我想我可以通過創建我自己的集合類型來解決這個問題,但我希望能夠簡單地修復當前的代碼。只是看看是否有可能。 – Jack