🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Varargs

A varargs parameter is a parameter that can take any number of arguments in one call. It is written with a star after the type, like Int*.

Any count of arguments, one total

total takes its numbers through an Int* parameter and adds them with sum. The three calls pass three, two, and one argument.

def total(nums: Int*): Int = nums.sum

@main def main(): Unit =
  println(total(1, 2, 3))
  println(total(10, 20))
  println(total(7))

Counting the arguments, even zero

length reports how many values arrived through the varargs parameter. The last call passes none, so the count is zero.

def count(nums: Int*): Int = nums.length

@main def main(): Unit =
  println(count(5, 6, 7))
  println(count(9))
  println(count())

Looping over the passed values

Inside printEach, a for loop visits the values in the order they were passed. Each value is printed on its own line.

def printEach(nums: Int*): Unit =
  for n <- nums do
    println(n)

@main def main(): Unit =
  printEach(7, 8, 9)

Example

def report(nums: Int*): Unit =
  println(nums.length)
  println(nums.sum)
  for n <- nums do
    println(n * 10)

@main def main(): Unit =
  report(2, 3, 4)

Key points

  • Varargs: Writing Int* after a parameter name lets that parameter accept any count of Int arguments.
  • Zero arguments: A varargs call can pass no arguments at all, and the parameter is then empty.
  • A sequence inside: Inside the function, the arguments act like a sequence, meaning a group of values in order.
  • Length: The length of that sequence tells how many arguments were passed.
  • Sum: The sum method adds up all the numbers in the sequence.
  • Looping: A for loop can visit each passed value one at a time.

In this example, report receives three arguments through its Int* parameter. It first prints the length, which is 3, and then the sum, which is 9. The for loop then prints each value times ten, in the order the values were passed.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

With def total(nums: Int*): Int = nums.sum, what does total() give back?