在scala的Seq中添加一个项目

Add an item in a Seq in scala

我正在使用 slick 使用 scala play 2。 我有一个像

这样的序列
val customerList: Seq[CustomerDetail] = Seq(CustomerDetail("id", "status", "name"))

我想在此 customerList 中添加一个 CustomerDetail 项目。我怎样才能做到这一点? 我已经试过了

customerList :+ CustomerDetail("1", "Active", "Shougat")

但这没有任何作用。

两件事。当您使用 :+ 时,操作是 左关联 ,这意味着您调用方法的元素应该在左侧。

现在,Seq(如您的示例中所用)指的是 immutable.Seq。当您追加或前置一个元素时,它 returns 一个包含额外元素的 新序列 ,它不会将它添加到现有序列中。

val newSeq = customerList :+ CustomerDetail("1", "Active", "Shougat")

但是附加一个元素意味着遍历整个列表以添加一个项目,考虑前置:

val newSeq = CustomerDetail("1", "Active", "Shougat") +: customerList

一个简化的例子:

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

scala> val newSeq = 0 +: original
newSeq: Seq[Int] = List(0, 1, 2, 3, 4)

可能值得指出的是,虽然 Seq 附加项运算符 :+ 左结合 ,但前置运算符 +:,是右结合

因此,如果您有一个包含 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所述:

A mnemonic for +: vs. :+ is: the COLon goes on the COLlection side.

在处理集合的集合时忽略这一点会导致意想不到的结果,即:

scala> SeqOfLists +: List("foo2", "bar2")
res2: List[Object] = List(List(List(foo, bar)), foo2, bar2)