Add item to Seq in scala

I work with scala play 2 with a spot. I have a Seq like

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

I want to add a CustomerDetail element to this customer list. How can i do this? I have already tried

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

But it does nothing.

+4
source share
2 answers

Two things. When you use :+, the operation remains associative, that is, the element that you are calling, the method should be on the left.

Now Seq(as used in your example) refers to immutable.Seq. When you add or add an element, it returns a new sequence containing an additional element, it does not add it to an existing sequence.

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)
+6

, , Seq append item :+ , prepend +: .

, Seq List:

scala> val SeqOfLists: Seq[List[String]] = Seq(List("foo", "bar"))
SeqOfLists: Seq[List[String]] = List(List(foo, bar))

"elem" Seq, :

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:

+: vs.: + is: COLON COLMENT.

, :

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

Source: https://habr.com/ru/post/1653742/


All Articles