1. Overview
In this tutorial, we’ll learn how to repeat a character or several characters multiple times in Scala using only the standard library.
2. Using the String Multiplication Method
The standard lib provides a very easy solution for this through the StringOps class, which provides many extension functions for Strings:
scala> "a" * 3
res0: String = aaa
scala> "abc" * 3
res1: String = abcabcabc
A very small detail is that we cannot use Chars directly here, otherwise it won’t work:
scala> 'a' * 3
res2: Int = 291
scala> 'a'.toString * 3
res3: String = aaa
We need to convert the Char into a String, otherwise, it will implicitly convert the character into an Int and then do a normal arithmetic multiplication.
3. Using the List.fill() Method
Another way to do this is using the List.fill() method:
scala> List.fill(3)('a')
res9: List[Char] = List(a, a, a)
scala> List.fill(3)('a').mkString
res10: String = aaa
scala> List.fill(3)("abc").mkString
res11: String = abcabcabc
This solution works with either Chars or Strings. It will create a List with as many repeated elements as we want. Then, we just need to convert them into a string using the List.mkString() method.
4. Conclusion
In this article, we learned how to easily repeat a given Char or String multiple times using only the Scala standard library. We leveraged both the List.fill() method and the StringOps extension method to produce a very simple one-liner solution.