Composite Design Pattern in Scala The following is a personal attempt at implementing the Composite design pattern in Scala. Observation is abstract...

class CompositeObservation(obss: Observation*) extends Observation {
  val elements: MutableList[Observation] = new MutableList[Observation]()

  elements ++ obss

  def hasElement(o: Observation): Boolean = elements.contains(o);
}


hasElement fails to return if an element is contained in the composite. Questions:


Am I misinterpreting the ++ operator? The Observation*?
What is the most ideomatic way to implement this pattern in Scala?
++ returns a new collection, you need ++= here
Your attempt looks fine to me. Maybe you should additionally implement the Traversable trait or so, and delegate the calls to elements in order to make things a little bit more convenient.


[Edit]

class CompositeObservation(obss: Observation*) 
     extends Observation with Traversable[Observation] {

  val elements = new MutableList[Observation]()

  elements ++= obss

  def hasElement(o: Observation): Boolean = elements.contains(o);

  def foreach[U](f: (Observation) =&gt; U): Unit = elements.foreach(f)
}