Adding a tuple to a set does not work

时光毁灭记忆、已成空白 提交于 2020-01-21 04:28:50

问题


scala> val set = scala.collection.mutable.Set[(Int, Int)]()
set: scala.collection.mutable.Set[(Int, Int)] = Set()

scala> set += (3, 4)
<console>:9: error: type mismatch;
 found   : Int(3)
 required: (Int, Int)
              set += (3, 4)
                  ^

scala> set += Tuple2(3, 4)
res5: set.type = Set((3,4))

Adding (3, 4) does not work - why ?

Normally, (3, 4) also represents a tuple with two elements.


回答1:


The issue is that it exists in the Set trait a method +(elem1: A, elem2: A, elems: A+) and the compiler is confused by it. It actually believes that you try to use this method with 2 Int parameters instead of using it with a tuple, as expected.

You can use instead: set += (3 -> 4) or set += ((3, 4))



来源:https://stackoverflow.com/questions/11825765/adding-a-tuple-to-a-set-does-not-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!