1

I want to add an element to the end of a seq in scala. But it didn't work. Can somebody help ? Thanks

val data = Seq(
  Vectors.dense(1.0, 2.0),
  Vectors.dense(2.0, 4.0),
  Vectors.dense(3.0, 6.0)
)
data :+ Vectors.dense(4.0, 8.0) // didn't work
println(data)

Result shown
println shows List([1.0,2.0], [2.0, 4.0], [3.0,6.0])

Mincong Huang
  • 5,284
  • 8
  • 39
  • 62
  • 1
    The documentation for the `:+` method on [`Seq`](http://www.scala-lang.org/api/current/#scala.collection.Seq) contains an example which is almost exactly the same as the code in your question. – Chris Martin Aug 24 '15 at 08:52

1 Answers1

6

Seq is immutable structure. When you added new element to it, new structure was created and returned, but val "data" remained the same.

Try

val newData = data :+ Vectors.dense(4.0, 8.0)
println(newData)
Tyth
  • 1,774
  • 1
  • 11
  • 17
  • 1
    Also there are http://www.scala-lang.org/api/2.11.4/index.html#scala.collection.mutable.Seq – oluies Aug 24 '15 at 08:43
  • If i want to create a foreach loop and add a vector at each time, what should i use instead of seq, as it is immutable ? – Mincong Huang Aug 24 '15 at 08:49
  • 1
    you can use the mutable sec internal to a method and then return the mutable instance. Using the immutable may be as fast. Note http://docs.scala-lang.org/overviews/collections/performance-characteristics.html – oluies Aug 24 '15 at 08:51
  • More likely you just want to use `map` instead of `foreach`, though. – Chris Martin Aug 24 '15 at 08:54
  • @oluies mutable.Seq does not support appending or prepending to sequence http://stackoverflow.com/questions/6626238/how-to-append-or-prepend-on-a-scala-mutable-seq – ymonad Aug 24 '15 at 08:54
  • read the whole http://docs.scala-lang.org/overviews/collections/introduction.html – oluies Aug 24 '15 at 08:57