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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.