首页 文章

在scala中的Seq中添加项目

提问于
浏览
5

我正在使用光滑的scala play 2 . 我有一个Seq喜欢

val customerList: Seq[CustomerDetail] = Seq(CustomerDetail("id", "status", "name"))

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

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

但这没有做任何事情 .

2 回答

  • 7

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

    现在, Seq (在您的示例中使用)引用 immutable.Seq . 附加或前置元素时,它返回包含额外元素的新序列,但不会将其添加到现有序列中 .

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

    但附加元素意味着遍历整个列表以添加项目,请考虑预先添加:

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

    一个简化的例子:

    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)
    
  • 1

    值得指出的是,虽然 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))
    

    如_1697377中所述:

    一个助记符:vs.:is:COLon进入COLlection一侧 .

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

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

相关问题