1. Overview

In this tutorial, we’ll learn how to reverse a String in Scala using only the standard library.

2. Using a Loop

The most naive approach is to use a loop in reverse:

scala> val s = "abcde"
s: String = abcde

scala> (for(i <- 0 to s.size - 1) yield s(s.size - 1 - i)).mkString
res0: String = edcba

We loop using the String size and get the characters starting from the end. Then, we join every character again using the String.mkString() method.

Using this approach, we need to do some arithmetic. We can rearrange the loop to make it a bit cleaner:

scala> (for(i <- s.size - 1 to 0 by -1) yield s(i)).mkString
res1: String = edcba

In this approach, we cleaned the code by making the index starting with the String size and decreasing on each iteration, sounding more natural.

3. Using the String.reverse() Method

An even cleaner solution is to use the native String.reverse() method that will do this for us:

scala> s.reverse
res1: String = edcba

This is a convenient method from the Scala standard library.

4. Conclusion

In this article, we learned how to reverse a String using a loop and the native String.reverse() method.

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