Variadic Functions in Scala

Here’s a function that will take an arbitrary number of ints as arguments.

object VariadicFunctions {
  def sum(nums: Int*): Unit = {
    println(nums.mkString(" "))
    val total = nums.sum
    println(total)
  }

  def main(args: Array[String]): Unit = {
    sum(1, 2)
    sum(1, 2, 3)
    
    val nums = Array(1, 2, 3, 4)
    sum(nums: _*)
  }
}

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.

sum(1, 2)
sum(1, 2, 3)

If you already have multiple args in a sequence, apply them to a variadic function using :_* like this.

val nums = Array(1, 2, 3, 4)
sum(nums: _*)

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.

$ scalac VariadicFunctions.scala
$ scala VariadicFunctions
Array(1, 2)
3
Array(1, 2, 3)
6
Array(1, 2, 3, 4)
10

Another key aspect of functions in Scala is their ability to form closures, which we’ll look at next.

Next example: Closures.