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?
You have to use map::find() and map::insert(). find() returns an iterator to a map element, which is a pair<int, list>, or it returns end(). If the iterator == end(), you need to add a pair<int, list> to the map.
In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.
Concatenating and Multiplying Tuples Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.
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)
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