1

This code causes Stackoverflow error:

lazy val leftChild = new Node(true, root, Seq(2), Seq())
lazy val rightChild = new Node(true, root, Seq(3), Seq())
lazy val root :Node = new Node(false, null, Seq(1), Seq(leftChild, rightChild))

where Node is defined as follows:

case class Node(isLeaf: Boolean, parent: Node,  keys: Seq[Int], pointers: Seq[Node])

One possible solution would be to resign from using case class. How to properly implement this structure using immutable states only? Is this possible with lazy and Node as case class?

Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68
  • related:http://stackoverflow.com/questions/7507965/instantiating-immutable-paired-objects http://stackoverflow.com/questions/4978270/scala-circular-reference-while-creating-object – Siphor May 23 '15 at 13:05

1 Answers1

1

I think recursive call to a call-by-value arguments will always result in this infinite initialization loop. One way to go around this (as you have guessed) is to move away from case classes and add the parent to be call-by-name.

The implementation is immutable, the only problem is that it doesn't make use of case classes.

 lazy val root: Node  = new Node(false, null, Seq(1), Seq(leftChild, rightChild))
 lazy val leftChild = new Node(true, root, Seq(2), Seq())
 lazy val rightChild = new Node(true, root, Seq(3), Seq())


 class Node(val isLeaf: Boolean, parent: => Node,  val keys: Seq[Int], val pointers: Seq[Node]) {
     def getParent = parent
 }

 println(root)
 println(leftChild.getParent)
marios
  • 8,874
  • 3
  • 38
  • 62