Add An Item In A Seq In Scala


Answer :

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 sequence containing the extra element, it doesn't add it to the existing sequence.

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) 

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) 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable