Appending an element to the end of a list in Scala
That's because you shouldn't do it (at least with an immutable list).If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:
(4 :: List(1,2,3).reverse).reverse
or that:
List(1,2,3) ::: List(4)
Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List
; it's an immutable data structure, like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)
Instead of using lists for such use cases, I suggest to either use an ArrayBuffer
or a ListBuffer
. Those datastructures are designed to have new elements added.
Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:
scala> import scala.collection.mutable.ListBufferimport scala.collection.mutable.ListBufferscala> var fruits = new ListBuffer[String]()fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()scala> fruits += "Apple"res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)scala> fruits += "Banana"res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)scala> fruits += "Orange"res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)scala> val fruitsList = fruits.toListfruitsList: List[String] = List(Apple, Banana, Orange)