Adding to a List in Scala – another method

This is another method of adding to a list in Scala. You don’t change the original list but create another list using the ::: operator.

The only problem with this is that you are creating a new list with the single element followed by the original list. Here is an example:

object AddToAnotherList extends App {
  val list1 = List(1,2,3,4)
  println(s"List1 contains $list1")
  // Add contents of an extra list
  val list2 = list1 :+ 5
  println(s"List2 contains $list2")

The output is as follows:

List1 contains List(1, 2, 3, 4)
List2 contains List(1, 2, 3, 4, 5)

The reason for this convoluted method is that we avoid mutable state in Scala, so by default we use immutable lists. How do we ‘add’ to the list? We take the immutable list (1,2,3,4) and an immutable value (5) and add them together to form a new immutable value (5,1,2,3,4). We could use a mutable list or ListBuffer, but that’s not the Scala way.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s