Question

I want to create a Counter[A] data structure (inspired by Python's Counter) that extends Map[A, Int] that simply keeps counts of occurrences of items of type A. I want it to have 2 extra methods add(item: A) and remove(item: A) which increments/decrements counter associated with item and ofcourse I also want all the nice Scala collection methods like map, filter etc so I probably should be extending Map[A, Int]. But, I am confused regarding what are the minimal set of methods should I override/implement from Map for the other Scala collection methods to simply work.

Was it helpful?

Solution

Consider replacing inheritance with delegation. In other words, your class can extend Map[A, Int], but it should contain a private Map[A, Int] member. All calls to your class simply delegate the same calls to the member.

Here is a partial implementation of my suggestion:

class MyClass[A, Int] extends collection.immutable.Map[A, Int] {
  private val map = collection.immutable.Map.empty[A, Int]

  def get(key: A): Option[Int] = {
    map.get(key)
  }

  def iterator: Iterator[(A, Int)] = {
    map.iterator
  }

  def -(key: A): Map[A, Int] = {
    map - key
  }

  def +[B1 >: Int](kv: (A, B1)): Map[A, B1] = {
    map + kv
  }
}

OTHER TIPS

You should looks at this: http://docs.scala-lang.org/overviews/core/architecture-of-scala-collections.html It explains with details process of building new collections in scala. If you don't want to read whole article you can jump directly to section 'Integrating new sets and maps' which by example shows how to build new kind of map - exactly what you want to do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top