0
\$\begingroup\$

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?
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$
  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.

[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) => U): Unit = elements.foreach(f)
}
\$\endgroup\$
4
  • \$\begingroup\$ 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"? \$\endgroup\$ Sep 15, 2011 at 21:08
  • \$\begingroup\$ @Hugo S Ferreira: It's really easy. I added the code. \$\endgroup\$
    – Landei
    Sep 15, 2011 at 21:39
  • \$\begingroup\$ thx. I realize the : Unit = ... can be replaced by { ... } Any particular reason I'm not aware for you to have used it? \$\endgroup\$ Sep 16, 2011 at 10:21
  • \$\begingroup\$ 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. \$\endgroup\$
    – Landei
    Sep 16, 2011 at 21:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.