In a small library I'll try to write, the end user-facing part looks like this:
case class Box(is: Item*)
case class Item(data: Int)
Box(Item(0), Item(1))
Ideally, however, each item should know in which box it is:
case class Item(data: Int, box: Box)
Is there any way to establish this bidirectional connection with immutable case classes? I tried to avoid something like this...
val box = Box()
val i = Item(0, box)
box.add(i) // requires var in Box :(
or this:
val i = Item(0, None) // requires Option :(
val box = Box(i)
i.box = Some(box) // requires var in Item :(
...by using lazy and implicits but couldn't come up with a solution. Is it possible at all?
From the following question, I learned that pass-by-name + lazy could be useful, but still, the box would be required to be passed explicitly: [Scala: circular references in immutable data types?. The goal is to make the end user-facing part as simple/slim as possible, behind the scenes as much magic as required could be used :)