← Back to Scala Course | Chapter 5: Functions | Lesson 5 of 7

Variable Arguments (varargs)

Variable Arguments (varargs)

A parameter marked with *, like nums: Int*, accepts any number of arguments at the call site, collected internally as a Seq. Varargs must be the last parameter in the list. To pass an existing collection as varargs, you spread it with a trailing : _*.

Note: Use someSeq: _* to expand an existing collection into a varargs call, since you can't pass a Seq directly where individual arguments are expected.

Example: Variable Arguments (varargs)

markup
object Main extends App {
  def sumAll(nums: Int*): Int = {
    nums.sum
  }

  println(sumAll(1, 2, 3))
  println(sumAll(10, 20, 30, 40))

  val values = Seq(5, 10, 15)
  println(sumAll(values: _*))
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.