Scala Functions - Variable Arguments

Scala 函数Scala Functions

Scala allows you to indicate that the last parameter of a function can be repeated, meaning you do not need to specify the number of parameters, and can pass a variable-length argument list to the function.

Scala sets variable arguments (repeated parameters) by placing an asterisk after the type of the parameter. For example:

object Test {
   def main(args: Array[String]) {
        printStrings("Example", "Scala", "Python");
   }
   def printStrings( args:String* ) = {
      var i : Int = 0;
      for( arg <- args ){
         println("Arg value[" + i + "] = " + arg );
         i = i + 1;
      }
   }
}

Executing the above code produces the following output:

$ scalac Test.scala
$ scala Test
Arg value[0] = Example
Arg value[1] = Scala
Arg value[2] = Python

Scala 函数Scala Functions

Other Extensions