Learn Scala 3 Fast: Collections: Updating List Elements

Because List is immutable, the way you add, remove, and update elements is to (a) use its add/update/delete methods while (b) assigning the result to a new variable. The following examples begin to demonstrate this process. More examples are then shown in the Sequences: More Methods lesson that follows.

Appending and prepending elements

First, to append one element to a List, use its :+ method, and to add multiple elements, use its ++ method:

val a = List(1, 2, 3)
val b = a :+ 4             // add one element
val c = b ++ List(5, 6)    // add multiple elements

TIP: The :+ and ++ methods are used with both List and Vector.

Because List is a linked-list, the preferred way to work with it is to prepend elements to it:

val a = List(2, 3)    // List(2, 3)
val b = 1 :: a        // List(1, 2, 3)
val c = 0 :: b        // List(0, 1, 2, 3)

With the List class, prepending is actually a faster operation than appending, but when your lists are small, this isn’t a huge concern.

Removing elements

There are many ways to remove elements from a List, and I cover those in the Sequences: More Methods lesson. As a quick preview of that lesson, a common approach is to use the List class filter method, like this:

val a = List(1, 2, 3, 4, 5)
val b = a.filter(_ > 3)        // b: List(4, 5)

I don’t want to duplicate that lesson too much, but for this lesson I just want to give you a preview of one way to “remove” elements from a List (remembering to assign the result to a new List).

Updating elements

There are also many ways to update a List, so I’ll just share one approach here that truly lets you update an element according to its position in the list:

val a = List(1, 2, 3)
val b = a.updated(0, 100)    // b: List(100, 2, 3)
val c = b.updated(1, 200)    // c: List(100, 200, 3)

The first call to the updated method updates the value at index 0 in the list, giving it a new value of 100. The second call then updates the value at index 1 in the list, giving it a new value of 200.

For more examples of the methods you can use, see the Sequences: More Methods lesson. Or, if you’re really curious and want to see many more examples, see my blog post, 100+ Scala List class examples.

Exercises

The exercises for this lesson are available here.