Variable Length Arguments
Most of the programming languages support the notion of variable length argument.
Scala is not an exception. It allows you
to indicate that the last argument of a function is a variable length argument. So
may be repeated multiple times.
Here is an example.
def echo(s:String*) = s foreach println //You can use it like this. echo("One","Two","Three") //You can pass as many arguments as you want. echo("One","Two","Three", "Four", "Five") //Even no arguments is fine echo()
You just need to remember few important observations.
The variable argument must be the last argument
So, the following code is invalid.
def echo(s:String*, i:Int) = s foreach println
All of the variable argument values are of the same data type
If the variable argument is of type Int, you can pass n number of Integers. However, you cannot mix in a string with them.
The variable argument is available to the function body as an array
In the above example, s is available to the function body as a string array. Since the type of s is a String, inside the body, s is an array of string. If we change the type of s to an Int, inside the body, s would be available as an array of Int.
Basics of Scala functions | Function Literals in Scala | Function values | Local Functions | Variable length argument | Default values and named arguments | Scala Placeholder syntax | Higher Order functions | Partially applied functions | Function currying