我有一个案例类Folder
:
case class Folder(children: List[Folder], parent: Folder)
以及创建其子项的函数:
def createChildrenWith(parent: Folder) = ???
我想将(self)-reference传递给构造函数中的createChildrenWith,如:
Folder(createChildrenWith(<ref-to-Folder>), Nil)
虽然self指的是当前正在构建的文件夹。
我该如何实现?
PS:parent =顶级文件夹的Nil。
答案 0 :(得分:1)
你可以使用懒惰。
class Folder(val name: String, p: => Option[Folder], c: => List[Folder]) {
lazy val parent = p
lazy val children = c
}
object Main {
def main(args: Array[String]) {
lazy val topFolder: Folder = new Folder("F1", None, List(c1, c2, c3))
lazy val c1: Folder = new Folder("C1", Some(topFolder), List.empty)
lazy val c2: Folder = new Folder("C2", Some(topFolder), List.empty)
lazy val c3: Folder = new Folder("C3", Some(topFolder), List.empty)
println(topFolder.children.head.parent.map(_.name).get)
}
}
但是,我个人会寻找没有循环引用的解决方案。