可能值得指出的是,虽然Seq 追加项目运算符:+ 是左关联,但前置运算符+: 是右关联 em>。
所以如果你有一个带有List 元素的Seq 集合:
scala> val SeqOfLists: Seq[List[String]] = Seq(List("foo", "bar"))
SeqOfLists: Seq[List[String]] = List(List(foo, bar))
并且你想在 Seq 中添加另一个“elem”,追加是这样完成的:
scala> SeqOfLists :+ List("foo2", "bar2")
res0: Seq[List[String]] = List(List(foo, bar), List(foo2, bar2))
并且预先以这种方式完成:
scala> List("foo2", "bar2") +: SeqOfLists
res1: Seq[List[String]] = List(List(foo2, bar2), List(foo, bar))
如API doc中所述:
+: 与 :+ 的助记符是:COLon 在 COLlection 一侧。
在处理集合的集合时忽略这一点可能会导致意想不到的结果,即:
scala> SeqOfLists +: List("foo2", "bar2")
res2: List[Object] = List(List(List(foo, bar)), foo2, bar2)