Scala集合:+与++的区别

4

+ 和 ++ 在应用于集合时有什么不同?

scala> val set = Set[String]("a","b")
set: scala.collection.immutable.Set[String] = Set(a, b)

scala> set + "c"
res2: scala.collection.immutable.Set[String] = Set(a, b, c)

scala> set ++ "c"
res3: scala.collection.immutable.Set[Any] = Set(a, b, c)

第一个返回Set[String],而第二个返回Set[Any]。 看起来++更加通用,但是++的附加值到底是什么?

5个回答

9
这应该会让它更清晰明了:
 ( set ++ "c") contains "a"  // true; "a" is a String in this set.


 ( set ++ "c") contains "c"  // false, "c" is a NOT a string in this set.

 ( set ++ "c") contains 'c'  // true, 'c' is a CHAR in this set.

因此,( set ++ "c") 将产生一个包含原始的 Set[String],其中包含 "a""b",现在还包含了一个 'c',它是一个 Char,因此 ( set ++ "c") 的类型现在是 Set[Any]

字符串 "c" 可以被视为可遍历的 Chars,而集合上的 ++ 方法接受可遍历对象。


2
scala> set ++ "ca" res2: scala.collection.immutable.Set[Any] = Set(a, b, c, a) - twillouer
2
是的,那是一个包含 "a", "b", 'c''a'Set[Any] - Faiz

3

来自 scaladoc

看起来 + 是用来直接添加元素的,而 ++ 则是用来从另一个集合中添加元素的。

也许 "c" 会被转换成一个集合,如果是这样,那么这个方法可能会更加复杂,因为需要创建一个临时对象。


2
如果您查看 Set 的 ++ 方法的 API 文档,您会发现它需要一个 GenTraversableOnce。
scala> val c:GenTraversableOnce[Any] = "c"
c: scala.collection.GenTraversableOnce[Any] = c

这意味着在这种情况下:
scala> set ++ "c"
res3: scala.collection.immutable.Set[Any] = Set(a, b, c)

"c" 是一个 GenTraversableOnce[Any],然后 ++ 方法会添加该集合中的所有元素。
更好的例子是:
scala> set ++ "cd"
res1: scala.collection.immutable.Set[Any] = Set(a, b, c, d)

我怀疑像其他回答者一样,我只是在Scala控制台中稍微调整了一下,以检查并再次检查它是否通过隐式转换实现。是的,看起来是这样的。

2
Karthik T是正确的,String(编辑:隐式转换为)是一个集合,因此您可以在这里使用 ++ 。正如您所看到的,结果集不再是 Set [String] 类型,而是 Set [Any] 类型。这是因为 String 是 Char 的集合,而 String 和 Char 的公共超类型是 Any 。

1
实际上,String本身并不是一个集合,但有隐式转换使其成为集合。 - om-nom-nom
我们可以看到这个错误信息:scala> val s : Set[String] = set ++ "c" <console>:8: 错误: 类型不匹配; 找到 : scala.collection.immutable.Set[Any] 需要的是: Set[String] 注意: Any >: String, 但是 trait Set 在类型 A 上是不变的。 您可能希望探索通配符类型,例如 _ >: String。(SLS 3.2.10) val s : Set[String] = set ++ "c" - twillouer
@om-nom-nom,谢谢您的澄清,我应该提到那个。 - drexin

0

在你的REPL中尝试一下,看看有什么明显的区别

val set = Set[Int](1,2)

set + 3 //res0: = ...set[Int] = (1,2,3)
set + Set[Int](3,4)  //Type mismatch
set ++ Set[Int](3,4) //res5: ...set[Int] = (1,2,3,4)

如果要将Set添加到另一个Set中,请使用 ++ 如果要将元素添加到Set中,请使用 +

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接