为什么在 Scala 中附加到 Seq 的(复制)被定义为 :+ 而不仅仅是像 Set 和 Map 中的 +?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12124834/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why (copy) appending to Seq in Scala is defined as :+ and not just + as in Set and Map?
提问by thesamet
Scala's Map and Set define a +operator that returns a copy of the data structure with a single element appended to it. The equivalent operator for Seqis denoted :+.
Scala 的 Map 和 Set 定义了一个+运算符,该运算符返回数据结构的副本,其中附加了单个元素。的等效运算符Seq表示为:+。
Is there any reason for this inconsistency?
这种不一致有什么原因吗?
回答by om-nom-nom
Map and Set has no concept of prepending (+:) or appending (:+), since they are not ordered. To specify which one (appending or prepending) you use, :was added.
Map 和 Set 没有前置 ( +:) 或附加 ( :+) 的概念,因为它们是无序的。要指定您使用的(附加或前置),:已添加。
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)
Don't get confused by the order of arguments, in scala if method ends with : it get's applied in reverse order(not a.method(b) but b.method(a))
不要被参数的顺序弄糊涂,在scala中,如果方法以:它以相反的顺序应用(不是a.method(b)而是b.method(a))
回答by psp
FYI, the accepted answer is not at all the reason. This is the reason.
仅供参考,接受的答案根本不是原因。这就是原因。
% 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)
Never underestimate how long are the tendrils of something like any2stringadd.
永远不要低估像 any2stringadd 这样的东西的卷须有多长。

