Variable Arguments (varargs)
In this page:
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
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: