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

Variable Arguments (varargs)

Varargs let a function take any number of inputs of the same kind, like a bag that holds as many items as you bring. Inside, they become one list.
Syntax
scala
def function_name(nums: Int*): ReturnType = {
  // nums behaves like a Seq
}

function_name(value1, value2, value3)

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: _*))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Passing a List directly to a varargs parameter such as sumAll(myList), when it must be expanded with sumAll(myList: _*).
  2. Putting the * parameter before other parameters, when it must be the last one.
  3. Expecting nums to be an Array, when it is a Seq inside the function.
🔒

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.