8

Why does this work:

val x = Map[Int,Int]()
val y = (1, 0)
x + y

but not this?

val x = Map[Int,Int]()
x + (1, 0)

The error produced is:

<console>:11: error: type mismatch;
found   : Int(1)
required: (Int, ?)
          x + (1,0)
               ^

If I were to enter (1,0) into the REPL, it correctly types it as (Int,Int).

I should add that this works fine:

x + (1 -> 0)
kanielc
  • 1,268
  • 1
  • 12
  • 14

2 Answers2

6

This is an ambiguity caused by the similarity between the notation for tuples and the one for parameter lists :

x + (1,0) is notation for x.+(1,0) but sadly there is no method on x that takes two Int parameters. What you want is x.+((1,0)), i.e. x + ((1,0)).

There is something in Scala called auto-tupling, see this question and answers, which rewrites, for example, println (1,2) to println((1,2)). Except this will not work here because the + method takes a variable number of arguments and not a single one like println.

You get that strange error message because it expect every value in your parameter list (1,0) to be a tuple, as in myMap + ((1,2), (1,3), (3,4)). It finds an Int instead of a (Int, Int), hence the error.

Community
  • 1
  • 1
gourlaysama
  • 11,240
  • 3
  • 44
  • 51
2

add another pair of parentheses to make it work:

val x = Map[Int,Int]()
x + ((1, 0))
Jiri Kremser
  • 12,471
  • 7
  • 45
  • 72