Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 18, 2024
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.
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.
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:
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 = "
"
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"
In this short article, we saw how to use repeated parameters in Scala.