Appending an element to the end of a list in Scala

Masiar picture Masiar · Oct 17, 2011 · Viewed 218.1k times · Source

I can't add an element of type T into a list List[T]. I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?

Answer

Landei picture Landei · Oct 17, 2011
List(1,2,3) :+ 4

Results in List[Int] = List(1, 2, 3, 4)

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).