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?
asked Sep 15, 2011 at 16:49
\$\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)
}
answered Sep 15, 2011 at 18:39
\$\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\$ Commented Sep 15, 2011 at 21:08
  • \$\begingroup\$ @Hugo S Ferreira: It's really easy. I added the code. \$\endgroup\$ Commented 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\$ Commented 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\$ Commented Sep 16, 2011 at 21:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.