Erhan Bagdemir
Erhan Bagdemir

Reputation: 5327

Case Class' Constructor with self-reference

I have a case class Folder:

case class Folder(children: List[Folder], parent: Folder)

and a function which creates its children:

def createChildrenWith(parent: Folder) = ??? 

I want to pass the (self)-reference to the createChildrenWith within the constructor like:

Folder(createChildrenWith(<ref-to-Folder>), Nil) 

while self is referring to the Folder that is currently being constructed.

How can I implement this?

PS: parent = Nil for top-level folder.

Upvotes: 1

Views: 1132

Answers (1)

Hyun Min Choi
Hyun Min Choi

Reputation: 49

You could use 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) 
  }
}

However, I would personally look for a solution without circular references.

Upvotes: 2

Related Questions