Scala Function with Variable Arguments

Advertisements


Scala allows you to indicate that the last parameter to a function may be repeated. This allows clients to pass variable length argument lists to the function. Following is a simple example to show the concept.

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

When the above code is compiled and executed, it produces the following result:

C:/>scalac Test.scala
C:/>scala Test
Arg value[0] = Hello
Arg value[1] = Scala
Arg value[2] = Python

C:/>

Here, the type of args inside the printStrings function, which is declared as type "String*" is actually Array[String].



Advertisements
Advertisements