1. Overview

In this short tutorial, we’ll see how to use the repeated parameters feature in Scala.

This language feature is not exclusive to Scala, as many other programming languages have a similar feature. In some of them, like Java, this feature can also be known as varargs, but it’s the same concept.

2. Repeated Parameters in Scala

In languages that do not offer support for repeated parameters, developers need to create an array or list to send multiple arguments. Sometimes this becomes cumbersome, and we end up with boilerplate code.

2.1. Defining a Function with Repeated Parameters

In Scala internals, repeated parameters are treated as an array, which can be empty as well. So if our method receives a repeated parameter, we can do whatever we’d do with an array:

scala> def myFunction(times: Int, strings: String*): String = {
     | (strings.mkString(" ") + "\n") * times
     | }
def myFunction(times: Int, strings: String*): String

However, there are some rules we need to take into account when using repeated parameters:

  • Repeated parameters are always the last method parameter
  • Repeated parameters should be of the same type (i.e., you cannot send an int and a String)
  • A method can have, at most, a single repeated parameter

2.2. Calling a Function with Repeated Parameters

Calling the function we defined earlier is now straightforward. For example, let’s call it with three String parameters:

scala> myFunction(3, "scala", "is", "awesome") 
val res0: String = 
"scala is awesome 
scala is awesome 
scala is awesome "

Furthermore, we can call a function with no strings for the repeated parameter as well. By doing so in our function, we’ll obtain three new lines:

scala> myFunction(3)
val res1: String = "
 
 
"

2.3. The Splat Operator

In some situations, we already have a List, but the method we are invoking requires repeated parameters. If we tried to send the list, we’d get an error:

scala> val lst = List("Scala", "is", "awesome")
val lst: List[String] = List(Scala, is, awesome)

scala> myFunction(3, lst)
                     ^
error: type mismatch;
found   : List[String]
required: String

In this case, we need to use the splat operator that will convert a collection into a valid input for a repeated parameter:

scala> myFunction(3, lst:_*)
val res2: String =
"Scala is awesome
Scala is awesome
Scala is awesome"

3. Conclusion

In this short article, we saw how to use repeated parameters in Scala.

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