Instantiating immutable paired objects

久未见 提交于 2019-11-26 07:37:05

问题


Is it possible to create a class with an immutable reference to a partner object, or does it have to be a var that I assign after creation?

e.g.

class PairedObject (p: PairedObject, id: String) {
  val partner: PairedObject = p  // but I need ref to this object to create p!
}

or similarly how could I instantiate the following pair?

class Chicken (e: Egg) { 
  val offspring = e
}

class Egg (c: Chicken) {
  val mother = c
}

回答1:


Here is a complete solution to the Chicken/Egg problem:

class Chicken (e: =>Egg) { 
  lazy val offspring = e 
}

class Egg (c: =>Chicken) {
  lazy val mother = c
}

lazy val chicken: Chicken = new Chicken(egg)
lazy val egg: Egg         = new Egg(chicken)

Note that you have to provide explicit types to the chicken and egg variables.

And for PairedObject:

class PairedObject (p: => PairedObject, val id: String) {
  lazy val partner: PairedObject = p
}

lazy val p1: PairedObject = new PairedObject(p2, "P1")
lazy val p2: PairedObject = new PairedObject(p1, "P2")



回答2:


If your problem is circular references, you could use the solution posted in this SO question:

scala: circular reference while creating object?

This solves the chicken/egg problem.



来源:https://stackoverflow.com/questions/7507965/instantiating-immutable-paired-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!