Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding value to Scala map

Tags:

map

scala

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)
like image 445
kanielc Avatar asked Jul 20 '13 11:07

kanielc


People also ask

How do I add values to a map in Scala?

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.

How do I add values to a list in Scala?

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”.

How do you add a mutable map?

Add elements to a mutable map by simply assigning them, or with the += method. Remove elements with -= or --= . Update elements by reassigning them.


1 Answers

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.

like image 57
gourlaysama Avatar answered Nov 07 '22 20:11

gourlaysama