Scala allows you to indicate that the last parameter of a function can be duplicated. This allows the customer to pass the variable-length argument list to the function. To mark a repeating parameter, place an asterisk after the type of the argument. For example:
Scala> def Echo
(args:string*) = for
(Arg <-args) println (ARG)
Echo: (string*) unit
This defines that echo can be invoked by 0 to multiple string arguments:
Scala> Echo ()
scala> Echo ("one")
one
scala> echo ("Hello", "world!")
Hello
world!
Inside a function, the type of the repeating parameter is an array that declares the parameter type. Thus, the type of args declared as type "string*" in the Echo function is actually array[string]. However, if you have an array of the appropriate type and try to pass it as a repeating parameter, you get a compiler error:
scala> val arr = Array
("What", "Up", "Doc?")
Arr:array[java.lang.string] = Array (What ' s, up, Doc?)
Scala> Echo (arr)
< console>:7:error:type mismatch;
found:array[java.lang.string]
required : String
Echo (arr)
ˆ
To implement this, you need to add a colon and a _* symbol after the array argument, like this:
Scala> Echo (arr: _*)
What ' s
up
Doc?
This annotation tells the compiler to take each element of arr as a parameter instead of passing it as a single argument to echo.