humbletrader
humbletrader

Reputation: 414

how to program against both mutable and immutable Map?

I want to write a function

def doSomething(m: Map[X, Y]): Z = ???

for some given types X, Y, Z.

The function will do the same thing for both immutable.Map and mutable.Map.

Is there any way I can write that?

Upvotes: 2

Views: 177

Answers (2)

linehrr
linehrr

Reputation: 1748

Both immutable.Map and mutable.Map extends scala.collection.Map.

package scala
package collection
trait Map[A, +B] extends Iterable[(A, B)] with GenMap[A, B] with MapLike[A, B, Map[A, B]] {
  def empty: Map[A, B] = Map.empty

  override def seq: Map[A, B] = this
}

looking above you will see this is a generic interface in Scala to describe a Map. therefore your function could be def doSomething(m: scala.collection.Map[X, Y]): Z = ???

you will still have majority of Map interface functions to use, however, those ones that's not shared between mutable and immutable won't be there.

Upvotes: 1

Andrey Tyukin
Andrey Tyukin

Reputation: 44918

Just declare the argument m to be of type collection.Map[X, Y].

Here is a quick way to find out what the least upper bound of the two types is:

import collection._
def f(a: mutable.Map[Int, Int], b: immutable.Map[Int, Int]) = List(a, b).head

The REPL with tell you that the return type is collection.Map[Int, Int].

Upvotes: 1

Related Questions