0
votes

Why below function is not work in scala?

def getUpdatedMap(keywords: String, m: Map[String, String]) : Map[String, String] = {
  m += (keywords -> "abcde")
}

Compilation error: value += is not a member of Map[String, String]

I'm quite new in Scala, any thing I have forget to define or missing? Thanks.

4

4 Answers

7
votes

You are confusing the immutable Map and the mutable Map.

// import mutable map as MutableMap
import scala.collection.mutable.{Map => MutableMap}

val mmap = MutableMap("a" -> 1)
mmap += "b" -> 2 // mutates original map
// mmap = Map(b -> 2, a -> 1)

// use immutable map
val imap = Map("c" -> 3)
val updatedIMap = imap.updated("d", 4) // returns a new updated immutable map
// imap = Map("c" -> 3)
// updateIMap = Map(c -> 3, d -> 4)
7
votes

You're not missing anything, exactly. Map just doesn't have a += method, as the compiler said. Check out the API docs.

I think the method you want here is +.

def +[B1 >: B](kv: (A, B1)): Map[A, B1]

Adds key/value pairs to this map, returning a new map.

def getUpdatedMap(keywords: String, m: Map[String, String]):
  Map[String, String] = m + (keywords -> "abcde")
1
votes

As everyone else said, immutable Map has no += method. Just want to add that maybe you confused it with compiler's shortcut for vars:

scala> var a = Map(1 -> 1)
a: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1)

scala> a += 2 -> 2

scala> a
res2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)

This += shortcut is the same as a = a + 2 -> 2, so it won't work for immutable values, like input parameters:

scala> def getMutated(m: Map[Int, Int]) = {m = m + (1 -> 1)}
   <console>:7: error: reassignment to val
       def getMutated(m: Map[Int, Int]) = {m = m + (1 -> 1)}
                                             ^

You could declare a var inside your function, however the best and simplest way is to use + as someone else said.

0
votes

It's exactly what it says: you are calling the method += on m, which is a Map, but Map doesn't have a += method.

It's not quite clear to me what you are trying to achieve here, from the looks of it, this seems to be what you want:

def getUpdatedMap(keywords: String, m: Map[String, String]) = 
  m + (keywords -> "abcde")