1. Overview

In this tutorial, we’ll see how to iterate a Scala list backward using only the existing Scala standard syntax constructors.

2. Using a Reverse Loop

The first solution to iterate a Scala List backward that we’ll see is by doing a loop on the List index. If we just do a normal loop and try to print each element, we’d print the List elements in normal order:

scala> val lst = List(1,2,3,4,5)
lst: List[Int] = List(1, 2, 3, 4, 5)

scala> for (i <- 0 until lst.size) println(lst(i))
1
2
3
4
5

But we can adapt this loop to print the elements in reverse order. The most naive solution would be to do some quick math on the index to start printing from the last element:

scala> for (i <- 0 until lst.size) println(lst(lst.size - 1 - i))
5
4
3
2
1

Notice that we need to subtract 1 from the index to avoid an IndexOutOfBoundsException on the first iteration. Either way, this feels a bit funky to read. There must be a better way, right? There sure is. Thankfully, Scala allows us to create a Range backward instead of the normal increasing Range we have been working with:

scala> for (i <- lst.size -1 to 0 by -1) println(lst(i))
5
4
3
2
1

Notice that we were able to create the decreasing range by adding the by -1 construct. This was possible by customizing the Range step.

3. Reversing the List

Another solution is to simply use the List.reverse() method:

scala> lst.reverse.foreach(println)
5
4
3
2
1

This solution is shorter and cleaner than the previous one. Unfortunately, it also has a downside regarding performance. The List.reverse() method returns a new list with elements in reversed order, which can be problematic for bigger lists.

4. Using the Reverse Iterator

In order to overcome the problems of the previous approach, we can get a reverse iterator of a List:

scala> lst.reverseIterator.foreach(println)
5
4
3
2
1

While the solution seems very similar to the one we saw in the previous section, it has the advantage of not creating a new List, hence being more performant.

5. Conclusion

In this article, we saw how to iterate a Scala List backward using a basic loop approach. We then moved to the more clean approach using the List.reverse() method. Unfortunately, this approach creates a new List every time. So, we moved to use the List.reverseIterator(), which avoids doing such an operation.

Comments are closed on this article!