Saurabh Saurabh - 2 months ago 17
Scala Question

How to remove multiple keys from a Map dynamically

Say I have a map like this:

scala> val a = Map("a"->2, "d" -> 4, "r" -> 5)
a: scala.collection.immutable.Map[String,Int] = Map(a -> 2, d -> 4, r -> 5)

I want to remove multiple keys dynamically from this. While I am able to do this:

scala> a - ("a","r")
res13: scala.collection.immutable.Map[String,Int] = Map(d -> 4)

But following fails:

scala> val keys = ("d","r")
as: (String, String) = (d,r)

scala> a - keys
<console>:15: error: type mismatch;
found : (String, String)
required: String
a - keys

While I understand this will be some casting issue, but I am not able to figure this simple thing out.


I also tried to make
as array, as in earlier example it became a Tuple, but that also fails.

scala> val keys = Array("d","r")
as: Array[String] = Array(d, r)

scala> a - keys
<console>:15: error: type mismatch;
found : Array[String]
required: String
a - keys

Answer Source

To remove multiple keys from a Map, you can use the -- method:

a -- Set("a", "r")

The following explains why you got the type mismatch error.

The version of the - method on Map that you're calling takes three arguments: the first two are keys to remove, and the third argument is a varargs for zero or more keys to remove in addition to the first two arguments. (The other version of - takes a single key as the argument.)

a - ("a", "r")

The above is not passing a tuple to the - method; it's passing two String arguments to the - method. In other words, the above is equivalent to:

a.-("a", "r")

When you do the below...

val keys = ("d", "r")
a - keys

...what you're doing is trying to pass a tuple as an argument to the - method. It's equivalent to:

a.-(("d", "r"))

That's why you get a type mismatch error when you try to pass a tuple to the - method. The - method expects one or more Strings.