maks
maks

Reputation: 6006

Scala Map += operation

Suppose I have next map:

import scala.collection.mutable._
val countries = Map[String, String](
    ("Paris", "France"), 
    ("Washington", "USA"),
    ("London", "England")
)

Then I try to add some values to that map(I get the values from command line arguments):

countries += (args(0), args(1))

But the above code doesn't compile saying that

found   : String
required: (String, String)

When I change that to

countries += ((args(0), args(1)))

or to

countries += (args(0) -> args(1))

then it compiles successfully. Why did the compiler not recognise a tuple in first case?

Upvotes: 1

Views: 167

Answers (2)

Impredicative
Impredicative

Reputation: 5069

From the Scaladoc:

def +=(elem1: (A, B), elem2: (A, B), elems: (A, B)*): Map.this.type adds two or more elements to this shrinkable collection.

In other words, there's an overloaded version of += that lets you add a number of elements at once. Your example looks like it's trying to do that (using the normal convention for multiple arguments), except that it's then complaining (rightly) that each of those arguments is of the wrong type.

Upvotes: 5

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

The compiler thought you were passing two parameters and interpreted your first parentheses as the delimiters of the parameter list.

Upvotes: 1

Related Questions