将元组添加到地图?

Kev*_*ith 5 scala

使用Scala 2.11.8,我可以key - value通过以下方式将一对附加到Map:

scala> Map( (1 -> 1) ) + (2 -> 2)
res8: scala.collection.immutable.Map[Int,Int] = Map(1 -> 1, 2 -> 2)
Run Code Online (Sandbox Code Playgroud)

但是,如何使用元组作为+的参数?

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

也不起作用:

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)
                           ^
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

可以,但是上面的为什么不呢?

eva*_*man 6

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

因此,例如,2 * 2等效于2.*(2),因为*它只是class的方法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)
Run Code Online (Sandbox Code Playgroud)