Variadic Functions in Scala
Here’s a function that will take an arbitrary number of int
s as arguments.
Within the function, the type of nums
is equivalent to Seq[Int]
. We can call nums.length
, iterate over it with for
or foreach
, and use various collection methods.
Variadic functions can be called in the usual way with individual arguments.
If you already have multiple args in a sequence, apply them to a variadic function using :_*
like this.
To run the program, save the code in a file named VariadicFunctions.scala
and use the scalac
command to compile it, and the scala
command to run it.
Another key aspect of functions in Scala is their ability to form closures, which we’ll look at next.
Next example: Closures.