Scala varargs syntax (and examples)

Scala FAQ: How do I use the Scala varargs syntax (or, What is the Scala varargs syntax)?

A Scala function with a varargs parameter

You can define a Scala function that accepts a varargs parameter like this:

def printAll(strings: String*): Unit =
    strings.map(println)

The part of this code that makes strings a varargs parameter is the * symbol after the String declaration, as highlighted in this line of code in the function declaration:

def printAll(strings: String*): Unit =
                            _

Calling a function with a varargs parameter

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 in 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 2 application that you can use to test with:

object ScalaVarargsTests {
    def main(args: Array[String]) {
       printAll("foo", "bar", "baz")
    }

    def printAll(strings: String*): Unit =
        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.