为什么(复制)附加到Scala中的Seq被定义为:+而不仅仅是在Set和Map中?

the*_*met 25 scala scala-collections

Scala的Map和Set定义了一个+运算符,该运算符返回一个数据结构的副本,并附加一个元素.Seq表示等效运算符:+.

这种不一致有什么理由吗?

om-*_*nom 50

Map和Set没有prepending(+:)或appending()的概念:+,因为它们没有被排序.要添加指定您使用的那个(附加或前置):.

scala> Seq(1,2,3):+4
res0: Seq[Int] = List(1, 2, 3, 4)

scala> 1+:Seq(2,3,4)
res1: Seq[Int] = List(1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)

不要对参数的顺序感到困惑,在scala中如果方法结束:它以相反的顺序应用(不是a.method(b)而是b.method(a))


psp*_*psp 20

仅供参考,接受的答案并非完全没有问题.这就是原因.

% scala27
Welcome to Scala version 2.7.7.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_06).

scala> Set(1, 2, 3) + " is the answer"
res0: java.lang.String = Set(1, 2, 3) is the answer

scala> List(1, 2, 3) + " is the answer"
warning: there were deprecation warnings; re-run with -deprecation for details
res1: List[Any] = List(1, 2, 3,  is the answer)
Run Code Online (Sandbox Code Playgroud)

永远不要低估像any2stringadd这样的卷须有多长.

  • 更清楚一点,这是由于List是协变的,但是Set是不变的,在我看来,这是一个比any2stringadd更大的问题. (6认同)