【问题标题】:Why (copy) appending to Seq in Scala is defined as :+ and not just + as in Set and Map?为什么(复制)在 Scala 中附加到 Seq 被定义为 :+ 而不仅仅是在 Set 和 Map 中的 +?
【发布时间】:2015-10-13 20:43:10
【问题描述】:

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

这种不一致有什么原因吗?

【问题讨论】:

    标签: scala scala-collections


    【解决方案1】:

    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)
    

    不要对参数的顺序感到困惑,在 scala 中,如果方法以 it get's applied in reverse order 结尾(不是 a.method(b) 而是 b.method(a))

    【讨论】:

      【解决方案2】:

      仅供参考,接受的答案根本不是原因。这就是原因。

      % 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)
      

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

      【讨论】:

      • 更清楚地说,这是由于 List 是协变的,而 Set 是不变的,在我看来,这是比 any2stringadd 更大的问题。
      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多