Scala Map, ambiguity between tuple and function argument list

val m = scala.collection.mutable.Map[String, Int]() // this doesn't work m += ("foo", 2) // this does work m += (("foo", 2)) // this works too val barpair = ("bar", 3) m += barpair 

So what does not work with m += ("foo" , 2) ? Scala gives an error like:

  error: type mismatch; found : java.lang.String("foo") required: (String, Int) m += ("foo", 2) ^ 

Apparently, Scala thinks I'm trying to call += with two arguments instead of a single tuple argument. What for? Isn’t this unambiguous, since I am not using m.+= ?

+7
source share
3 answers

Unfortunately ab (c, d, e, ..) desugars to ab(c, d, e, ..) . Hence the error.

+9
source

Isn't that unambiguous since I don't use m. + =?

No, it is not, because parentheses can always be used when there are several arguments. For example:

 List(1, 2, 3) mkString ("<", ", ", ">") 

So you may ask, what are some of the options? Well, the Scala API document is your friend (or mine, at least), so I present to you:

 scala> val m = scala.collection.mutable.Map[String, Int]() m: scala.collection.mutable.Map[String,Int] = Map() scala> m += (("foo", 2), ("bar", 3)) res0: m.type = Map(bar -> 3, foo -> 2) 

In other words, += accepts vararg.

+3
source

The preferred way to define map entries is to use the β†’ method. how

 m += ("foo" -> 2) 

What is the design of the tuple. a β†’ b gets desugared to .-> (b). Each object in scala has a β†’ method.

+2
source

All Articles