我不明白为什么+ =在我事先定义元组mapEntry然后将其添加到地图时工作,而尝试直接添加绕过创建不必要的变量mapEntry失败。很可能我错过了一些明显的东西。提前谢谢。
这适用:map + = mapEntry while 这失败了:map + =(“key-to-tom”,Person(“Tom”,“Marx”))
这是我完整的scala REPL会话
Welcome to Scala version 2.10.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_45).
Type in expressions to have them evaluated.
Type :help for more information.
scala> case class Person(val fname:String, val lname:String)
defined class Person
scala> val map = scala.collection.mutable.Map[String,Person]()
map: scala.collection.mutable.Map[String,Person] = Map()
scala> val mapEntry = ("key-to-joe", Person("Joe", "Smith") )
mapEntry: (String, Person) = (key-to-joe,Person(Joe,Smith))
scala> map += mapEntry
res0: map.type = Map(key-to-joe -> Person(Joe,Smith))
scala> val mapEntry2 = ("key-to-ann", Person("Ann", "Kline") )
mapEntry2: (String, Person) = (key-to-ann,Person(Ann,Kline))
scala> map += mapEntry2
res1: map.type = Map(key-to-joe -> Person(Joe,Smith), key-to-ann -> Person(Ann,Kline))
scala> map += ("key-to-tom", Person("Tom", "Marx") )
<console>:11: error: type mismatch;
found : String("key-to-tom")
required: (String, Person)
map += ("key-to-tom", Person("Tom", "Marx") )
^
阶&GT;
答案 0 :(得分:3)
您的上一个语句失败,因为您需要将元组括在括号中以表示您正在添加元组:
map += ( ("key-to-tom", Person("Tom", "Marx")) )
问题是+=
超载了。除了单个元组,+=
也可以带两个或更多个参数。签名是这样的:
def +=(elem1: (A, B), elem2: (A, B), elems: (A, B)*): Map.this.type
你的元组是Tuple2
(与Pair
相同,但仍然只是一个参数),这个重载方法需要2个参数(至少)。斯卡拉选择后者作为更接近的匹配。