Appending to Seq in Scala

The following code is supposed to append to a Seq, but it prints an empty list, what's wrong here?

object AppendToSeq extends App{ val x = Seq[Int]() x :+ 1 x :+ 2 println(x) } 

2 Answers

the value x created is an immutable Sequence and the method :+ defined on the immutable sequence return a new Seq object.

so your code should have x has a var (a mutable variable) and it should have its value re-assigned after each append (:+) operation as shown below.

scala> var x = Seq[Int]() x: Seq[Int] = List() scala> x = x :+ 1 x: Seq[Int] = List(1) scala> x = x :+ 2 x: Seq[Int] = List(1, 2) scala> x res2: Seq[Int] = List(1, 2) 
1

x :+ 1 creates a new Seq by appending 1 to the existing Seq, x, but the new Seq isn't saved anywhere, i.e. it isn't assigned to any variable, so it's just thrown away.

If you want to modify an existing Seq you can make the variable a var instead of a val. Then when you create a new Seq you can save it under the same name.

scala> var x = Seq[Int]() x: Seq[Int] = List() scala> x = x :+ 7 x: Seq[Int] = List(7) 
2

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa2xxaWeEcoKOmqepnZ6Ztq%2BzjK2mZquVpnqquoysmpqkkQ%3D%3D