scala - Reference to container for an item in the container -


in small library i'll try write, end user-facing part looks this:

case class box(is: item*) case class item(data: int)  box(item(0), item(1)) 

ideally, however, each item should know in box is:

case class item(data: int, box: box) 

is there way establish bidirectional connection immutable case classes? tried avoid this...

val box = box() val = item(0, box) box.add(i) // requires var in box :( 

or this:

val = item(0, none) // requires option :( val box = box(i) i.box = some(box) // requires var in item :( 

...by using lazy , implicits couldn't come solution. possible @ all?

from following question, learned pass-by-name + lazy useful, still, box required passed explicitly: [scala: circular references in immutable data types?. goal make end user-facing part simple/slim possible, behind scenes magic required used :)

you this:

case class box(is: (box => item)*) {   lazy val items = is.map(_(this)) } class item(val data: int, val box: box) object item {   def apply(data: int)(box: box): item = new item(data, box) }  val b = new box(item(0), item(1)) 

downsides box constructor bit weird, , item can no longer case class since relies on changing item object's apply method. gets exact same syntax creating objects , create circular references.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -