2016-10-24 114 views
3

使用斯卡拉2.11.8,我可以追加key - value对通过一个地图:将Tuple添加到地图?

scala> Map((1 -> 1)) + (2 -> 2) 
res8: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2) 

但我怎么可以使用元组作为+的说法?

scala> Map((1 -> 1)) + (2, 2) 
<console>:12: error: type mismatch; 
found : Int(2) 
required: (Int, ?) 
     Map((1 -> 1)) + (2, 2) 
         ^

也不这项工作:

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#+的签名是:

+(kv: (A, B)): Map[A, B],所以我不知道为什么它不工作。

编辑

scala> Map((1,1)).+((2, 2)) 
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2) 

作品,但为什么不上?

+4

'地图((1 - > 1))+((2,2))' – Jesper

+0

于是两个括号'((2,2))'由于第一需要的是通过参数传递给'( ';第二个'(''开始元组? –

+0

这是正确的。 – Iadams

回答

4

在Scala中,任何二进制操作(*,+等)实际上都是该操作中第一个元素类的方法。

因此,例如,2 * 2相当于2.*(2),因为*只是Int类的方法。

键入Map((1 -> 1)) + (2, 2)时发生了什么是Scala识别出您正在使用Map类的+方法。然而它认为你正试图将多个值传递给这个方法,因为它默认将开始参数解释为参数列表的开始(这是一个(合理的)设计决定)。

解决此问题的方法是将元组包装到另一对parens中或使用->语法(因为操作符优先级,因此使用parens)。

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)