Home Ask Login Register

Developers Planet

Your answer is one click away!

Francesco Peluso February 2016

How create new Scala Map class?

In Scala I want to create a generic new Map class called MyClass. In this class i want to maintain the generality of types and modify only method ++ for Sequence type. The ++ method must merge the equal object for the same key in this map.


val map1 = ("a"->Seq(1,2))
val map2 = ("a"->Seq(2,3))

the result must be

map1++map2 = ("a"->Seq(1,2,3))

and not

map1++map2 = ("a"->Seq(2,3))

For all other type MyMap must be the same of "classic" Map class.


slouc February 2016

As others have pointed out in the comments, you should try something first and then come back if you encounter some specific problem. Here's how you can start, given that you want to implement the Map trait:

class MyClass[A, +B] extends Map[A, B] {

  def get(key: A): Option[B] = ???
  def iterator: Iterator[(A, B)] = ???
  def +[B1 >: B](kv: scala.Tuple2[A, B1]): Map[A, B1] = ???
  def -(key: A): Map[A, B] = ???

  override def ++[B1 >: B](xs: scala.collection.GenTraversableOnce[scala.Tuple2[A, B1]]) = ???


You can also start from an existing Map implementation, such as

class MyClass[A, +B] extends scala.collection.immutable.HashMap[A, B] {

  override def ++[B1 >: B](xs: scala.collection.GenTraversableOnce[scala.Tuple2[A, B1]]) = ???


However, in that case compiler will warn you that inheritance from existing implementation is unwise because of implementation details.

Post Status

Asked in February 2016
Viewed 3,939 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life