-3

I need to append strings to a Seq. I declared the Seq below with val as the structure itself is immutable,even though I will change it by adding two elements. I read (see here) that the way to append an element to a Seq is with :+, and the code compiles fine but it prints an empty list List(). How to add elements to a Seq?

 val bands = Seq[String]()
 bands :+ "aaa"
 bands :+ "bbb"
 println(bands)
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • 2
    Please first read what's meaning of immutability and how it's handle in programming – cchantep Dec 29 '17 at 19:47
  • 4
    duplicate of [Add element to a list In Scala](https://stackoverflow.com/questions/19610320/add-element-to-a-list-in-scala) and [Appending an element to the end of a list in Scala](https://stackoverflow.com/questions/7794063/appending-an-element-to-the-end-of-a-list-in-scala) – prayagupa Dec 29 '17 at 19:56
  • The title of the SO question I referred to is misleading [Adding an item to an immutable Seq](https://stackoverflow.com/questions/8295597/adding-an-item-to-an-immutable-seq) – ps0604 Dec 29 '17 at 21:13

1 Answers1

1

The :+ function returns a new Sequence, since the default implementation of Seq is an immutable List.

Try println((bands :+ "aaa") :+ "bbb") or println(bands ++ List("aaa", "bbb")) instead.

Kraylog
  • 7,383
  • 1
  • 24
  • 35
  • Read [this](https://alvinalexander.com/scala/scala-idiom-immutable-code-functional-programming-immutability), it should help you understand the concept better and how to apply it. – Kraylog Dec 29 '17 at 19:50