在 Scala 的 Seq 中添加一个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39341729/
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
Add an item in a Seq in scala
提问by Md. Shougat Hossain
I am working with scala play 2 with slick. I have a Seq like
我正在与 slick 一起使用 scala play 2。我有一个像
val customerList: Seq[CustomerDetail] = Seq(CustomerDetail("id", "status", "name"))
I want to add a CustomerDetail item in this customerList. How can I do this? I already tried
我想在这个 customerList 中添加一个 CustomerDetail 项目。我怎样才能做到这一点?我已经试过了
customerList :+ CustomerDetail("1", "Active", "Shougat")
But this doesn't do anything.
但这没有任何作用。
回答by Yuval Itzchakov
Two things. When you use :+, the operation is left associative, meaning the element you're calling the method on should be on the left hand side.
两件事情。当您使用 时:+,操作是左关联的,这意味着您调用该方法的元素应该在左侧。
Now, Seq(as used in your example) refers to immutable.Seq. When you append or prepend an element, it returns a new sequencecontaining the extra element, it doesn't add it to the existing sequence.
现在,Seq(如您的示例中所用)指的是immutable.Seq. 当您附加或预先添加一个元素时,它会返回一个包含额外元素的新序列,它不会将它添加到现有序列中。
val newSeq = customerList :+ CustomerDetail("1", "Active", "Shougat")
But appending an element means traversing the entire list in order to add an item, consider prepending:
但是附加一个元素意味着遍历整个列表以添加一个项目,考虑预先添加:
val newSeq = CustomerDetail("1", "Active", "Shougat") +: customerList
A simplified example:
一个简化的例子:
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)
回答by TRuhland
It might be worth pointing out that while the Seqappend item operator, :+, is left associative, the prepend operator, +:, is right associative.
值得指出的是,虽然Seq追加项运算符:+, 是左关联的,但前置运算符+:, 是右关联的。
So if you have a Seqcollection with Listelements:
因此,如果您有一个Seq包含List元素的集合:
scala> val SeqOfLists: Seq[List[String]] = Seq(List("foo", "bar"))
SeqOfLists: Seq[List[String]] = List(List(foo, bar))
and you want to add another "elem" to the Seq, appending is done this way:
并且您想在 Seq 中添加另一个“元素”,追加是这样完成的:
scala> SeqOfLists :+ List("foo2", "bar2")
res0: Seq[List[String]] = List(List(foo, bar), List(foo2, bar2))
and prepending is done this way:
并且前置是这样完成的:
scala> List("foo2", "bar2") +: SeqOfLists
res1: Seq[List[String]] = List(List(foo2, bar2), List(foo, bar))
as described in the API doc:
A mnemonic for +: vs. :+ is: the COLon goes on the COLlection side.
+: 与 :+ 的助记符是:COLon 位于 COLlection 一侧。
Neglecting this when handling collections of collections can lead to unexpected results, i.e.:
在处理集合集合时忽略这一点可能会导致意外结果,即:
scala> SeqOfLists +: List("foo2", "bar2")
res2: List[Object] = List(List(List(foo, bar)), foo2, bar2)

