I am trying to define a “chained map” after http://steve-yegge.blogspot.com/2008/10/universal-design-pattern.html. I have run into a problem defining the companion object apply method. Here is what I have come up with:
import scala.collection.generic.ImmutableMapFactory
import scala.collection.immutable.HashMap
class ChainedMap[A, B](private val superMap: ChainedMap[A, B])
extends HashMap[A, B] {
override def get(key: A): Option[B] = {
if (contains(key)) {
get(key)
} else if (superMap != null) {
superMap.get(key)
} else {
None
}
}
}
object ChainedMap extends ImmutableMapFactory[ChainedMap] {
override def apply[A, B](superMap: ChainedMap[A, B],
elems: (A, B)*): ChainedMap[A, B] = {
// What goes here?
}
}
Here is how I will use it:
val parentMap = ChainedMap(null, "x" -> 1, "y" -> 2)
val childMap = ChainedMap(parentMap, "a" -> 42)
Well, extending Scala collections is tricky. There’s this reference, plus some blogs and Stack Overflow questions. However, you don’t need to do it, because it is already supported.