Scala FAQ: How do I use the Scala varargs syntax (or, What is the Scala varargs syntax)?
You can define a Scala function that accepts a varargs parameter like this:
def printAll(strings: String*) { strings.map(println) }
The only magic in using the varargs syntax is adding the *
symbol after the String declaration, as highlighted in this line of code in the function declaration:
def printAll(strings: String*) {
Once you've defined a function (or method) that accepts a varargs field, you can call that function like this:
printAll("foo")
this:
printAll("foo", "bar")
or this:
printAll("foo", "bar", "baz")
and so on.
Note: Within your function, such as my printAll
function, the variable strings is created as a Scala Array.
A complete Scala varargs example
If you'd like to experiment with this Scala varargs syntax on your own computer, here's the source code for a complete Scala class that you can use to test with:
object ScalaVarargsTests { def main(args: Array[String]) { printAll("foo", "bar", "baz") } def printAll(strings: String*) { strings.map(println) } }
Just save this in a file named something like varargs.scala
, and then run your tests with the Scala interpreter like this:
$ scala varargs.scala
As you can see, the Scala varargs syntax is simple. That's one thing I like about Scala, it's a very brief, "low ceremony" language.
For more details on how this works, see my tutorials, Scala’s missing splat/underscore operator _* (used as :_*), and How to create methods that take variable-arguments (varargs) fields.