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.
In this page:
Syntax
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)
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: _*))
}
Login to try C/C++/Java/PHP code in the editor
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
- Passing a
Listdirectly to a varargs parameter such assumAll(myList), when it must be expanded withsumAll(myList: _*). - Putting the
*parameter before other parameters, when it must be the last one. - Expecting
numsto be anArray, when it is aSeqinside the function.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: