\$\begingroup\$
\$\endgroup\$
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?
asked Sep 15, 2011 at 16:49
1 Answer 1
\$\begingroup\$
\$\endgroup\$
4
++
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 toelements
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
-
\$\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\$Hugo Sereno Ferreira– Hugo Sereno Ferreira2011年09月15日 21:08:36 +00:00Commented Sep 15, 2011 at 21:08
-
\$\begingroup\$ @Hugo S Ferreira: It's really easy. I added the code. \$\endgroup\$Landei– Landei2011年09月15日 21:39:49 +00:00Commented 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\$Hugo Sereno Ferreira– Hugo Sereno Ferreira2011年09月16日 10:21:32 +00:00Commented 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– Landei2011年09月16日 21:08:10 +00:00Commented Sep 16, 2011 at 21:08
lang-scala