我正在使用scala播放scala play 2。
我有一个像
val customerList: Seq[CustomerDetail] = Seq(CustomerDetail("id", "status", "name"))
我想在此customerList中添加一个CustomerDetail项。我怎样才能做到这一点?
我已经试过了
customerList :+ CustomerDetail("1", "Active", "Shougat")
但这没有任何作用。
最佳答案
两件事情。当您使用:+
时,该操作是左侧关联的,这意味着您要在其上调用该方法的元素应该在左侧。
现在,Seq
(在您的示例中使用)引用immutable.Seq
。当您追加或添加元素之前,它会返回一个包含额外元素的新序列,而不会将其添加到现有序列中。
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)
关于scala - 在Scala的Seq中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39341729/