Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add an item in a Seq in scala

Tags:

scala

seq

I am working with scala play 2 with slick. I have a Seq like

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("1", "Active", "Shougat")

But this doesn't do anything.

like image 919
Md. Shougat Hossain Avatar asked Sep 06 '16 06:09

Md. Shougat Hossain


Video Answer


1 Answers

It might be worth pointing out that while the Seq append item operator, :+, is left associative, the prepend operator, +:, is right associative.

So if you have a Seq collection with List elements:

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:

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.

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)
like image 84
TRuhland Avatar answered Sep 30 '22 03:09

TRuhland