Kevin Meredith
Kevin Meredith

Reputation: 41909

Add Tuple to Map?

Using Scala 2.11.8, I can append a key - value pair to a Map via:

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

But how can I use tuple as the +'s argument?

scala> Map( (1 -> 1) ) + (2, 2)
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1 -> 1) ) + (2, 2)
                          ^

Nor does this work:

scala> Map( (1, 1) ) + (2, 2)
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1, 1) ) + (2, 2)
                        ^
<console>:12: error: type mismatch;
 found   : Int(2)
 required: (Int, ?)
       Map( (1, 1) ) + (2, 2)
                           ^

Map#+'s signature is:

+(kv: (A, B)): Map[A, B], so I'm not sure why it's not working.

EDIT

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

works, but why doesn't the above?

Upvotes: 6

Views: 4802

Answers (1)

evan.oman
evan.oman

Reputation: 5572

In Scala, any binary operation (*,+, etc.) is actually a method of the class of the first element in the operation.

So, for example, 2 * 2 is equivalent to 2.*(2), because * is just a method of the class Int.

What is happening when you type Map( (1 -> 1) ) + (2, 2) is that Scala recognizes that you are using the + method of the Map class. However it thinks that you are trying to pass multiple values to this method because it defaults to interpreting the opening paren as the beginning of a parameter list (this is a (reasonable) design decision).

The way you resolve this is to wrap the tuple in another pair of parens or to use the -> syntax (with parens, because operator precedence).

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

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

Upvotes: 9

Related Questions