1

I don't understand why += works when I define a tuple mapEntry beforehand and then add it to a map, while trying to add directly bypassing creating of unnecessary variable mapEntry fails. Most likely I am missing something obvious. Thanks in advance.

This works: map += mapEntry while this fails: map += ("key-to-tom", Person("Tom", "Marx"))

Here is my complete scala REPL session

Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.

scala> case class Person(val fname:String, val lname:String)
defined class Person

scala> val map = scala.collection.mutable.Map[String,Person]()
map: scala.collection.mutable.Map[String,Person] = Map()

scala> val mapEntry = ("key-to-joe", Person("Joe", "Smith") )
mapEntry: (String, Person) = (key-to-joe,Person(Joe,Smith))

scala> map += mapEntry
res0: map.type = Map(key-to-joe -> Person(Joe,Smith))

scala> val mapEntry2 = ("key-to-ann", Person("Ann", "Kline") )
mapEntry2: (String, Person) = (key-to-ann,Person(Ann,Kline))

scala> map += mapEntry2
res1: map.type = Map(key-to-joe -> Person(Joe,Smith), key-to-ann -> Person(Ann,Kline))

scala> map +=  ("key-to-tom", Person("Tom", "Marx") )
<console>:11: error: type mismatch;
 found   : String("key-to-tom")
 required: (String, Person)
              map +=  ("key-to-tom", Person("Tom", "Marx") )
                   ^

scala>

1 Answer 1

3

Your last statement fails because you need to enclose the tuple in parentheses to convey that you are adding a tuple:

map +=  ( ("key-to-tom", Person("Tom", "Marx")) )

The problem is that += is overloaded. Aside from a single tuple, += also can take two or more arguments. The signature is this:

def +=(elem1: (A, B), elem2: (A, B), elems: (A, B)*): Map.this.type 

Your tuple is a Tuple2 (which is the same as a Pair but still just a single parameter), and this overloaded method takes 2 arguments (at least). Scala chooses the latter as the closer match.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, you can use map += "key-to-tom" -> Person("Tom", "Marx") syntax
Thanks for clear explanation. I was mesmerized by "def +=(kv: (A, B)): Map.this.type" and did not look down further.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.