1. Overview

In this tutorial, we’ll see how we can replace elements in a Scala List by index.

2. Replace Elements in a Scala List by Index

Here’s the List we’ll be working with:

scala> val lst = List('a', 'b', 'c', 'd')
val lst: List[Char] = List(a, b, c, d)

There are multiple ways to replace elements in a List. A common theme is that all of them follow Scala’s philosophy of immutability – a new List is returned, and the original List is not modified.

Let’s look at the different techniques.

2.1. Using the map() Method

The first solution we’ll look at is a naive approach. Given a List, we can map its elements together with the index:

scala> lst.zipWithIndex.map { case (elem, idx) => if idx == 2 then 'z' else elem }
val res0: List[Char] = List(a, b, z, d)

We should note that we make use of the zipWithIndex() method to add the index of each corresponding element. This allows us to operate based on the index as we want.

2.2. Using the updated() Method

While the previous approach worked just fine, there’s a more convenient solution using the updated() method:

scala> lst.updated(2, 'z')
val res1: List[Char] = List(a, b, z, d)

This is a bit more straightforward solution, with less boilerplate code.

2.3. Using the patch() Method

The last solution we’ll look into is using the patch() method which is a bit more powerful.

This method requires three arguments:

  • the index where to start replacing
  • a new Seq to replace
  • the length of the slice to be replaced

Let’s see how we can use it:

scala> lst.patch(2, Seq('z'), 1)
val res2: List[Char] = List(a, b, z, d)

In the example above, we replace the sub-sequence of size one that starts at index 2, with the element ‘z‘.

scala> lst.patch(2, Seq('z'), 2)
val res3: List[Char] = List(a, b, z)

In the example above, we replace the sub-sequence of size two that starts at index 2 (i.e., elements ‘b‘ and ‘c‘), with a single element ‘z‘. If we pass a bigger length also, it works just fine:

scala> lst.patch(2, Seq('z'), 3)
val res4: List[Char] = List(a, b, z)

scala> lst.patch(2, Seq('z', 'y'), 1)
val res5: List[Char] = List(a, b, z, y, d)

In the code above, we replaced a sub-sequence with a multi-element sequence.

3. Conclusion

In this article, we looked at different ways  to replace elements in a List by index.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.