Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 案例类别';带自引用的构造函数_Scala - Fatal编程技术网

Scala 案例类别';带自引用的构造函数

Scala 案例类别';带自引用的构造函数,scala,Scala,我有一个case class文件夹: case class Folder(children: List[Folder], parent: Folder) 以及创建其子级的函数: def createChildrenWith(parent: Folder) = ??? 我想在构造函数中传递对createChildrenWith的(自)引用,如下所示: Folder(createChildrenWith(<ref-to-Folder>), Nil) 文件夹(createChil

我有一个case class
文件夹

case class Folder(children: List[Folder], parent: Folder)
以及创建其子级的函数:

def createChildrenWith(parent: Folder) = ??? 
我想在构造函数中传递对createChildrenWith的(自)引用,如下所示:

Folder(createChildrenWith(<ref-to-Folder>), Nil) 
文件夹(createChildrenWith(),Nil)
而self指的是当前正在构造的文件夹

我如何实现这一点


PS:parent=Nil表示顶级文件夹。

您可以使用laziness

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) 
  }
}

但是,我个人会寻找一种没有循环引用的解决方案。

子文件夹应该如何引用父文件夹?已更新。谢谢你的关注。你从什么数据生成这些文件夹?你的问题还不清楚。比如说,我们正在为一些测试构建一个递归的随机文件夹结构,输入depth,表示树结构的深度,以及每个级别的子级数量的numOfItems。好吧,我也想到了这个主意。然而,在这种情况下,您需要编写自己的提取器,因为您不能再在模式匹配中使用文件夹。谢谢你的答复。