# 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:

1. Am I misinterpreting the ++ operator? The Observation*?
2. What is the most ideomatic way to implement this pattern in Scala?

1. ++ returns a new collection, you need ++= here
2. 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.

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) => U): Unit = elements.foreach(f)
}

• Thanks for the ++=. I like the idea of Traversable (akin to IEnumerable in C#). Could you provide me an example of how to do that "elengatly"? – Hugo Sereno Ferreira Sep 15 '11 at 21:08
• @Hugo S Ferreira: It's really easy. I added the code. – Landei Sep 15 '11 at 21:39
• thx. I realize the : Unit = ... can be replaced by { ... } Any particular reason I'm not aware for you to have used it? – Hugo Sereno Ferreira Sep 16 '11 at 10:21
• I copied the definiton of foreach from somewhere :-) But for beginners I would recommend to write out always the return type for methods, as it is easy to forget the = between arg list and method body (especially as ist looks like Java), and you search for hours why your method doesn't work. – Landei Sep 16 '11 at 21:08