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)
Adding new key-value pair We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
This is the first method we use to append Scala List using the operator “:+”. The syntax we use in this method is; first to declare the list name and then use the ':+' method rather than the new element that will be appended in the list. The syntax looks like “List name:+ new elements”.
Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With