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)
Seq
is immutable (and it probably is) but it doesn't have to be. – Boswell