Instantiating immutable paired objects

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")

Leave a Comment