Scala – Function with Variable Arguments

scala function with variable arguments

In this guide, we will discuss Scala Function with Variable Arguments. 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. Here, the type of args inside the print Strings function, which is declared as type “String*” is actually Array[String].

Try the following program, it is a simple example to show the function with arguments.

Example

object Demo {
   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;
      }
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Arg value[0] = Hello
Arg value[1] = Scala
Arg value[2] = Python

Next Topic : Click Here

This Post Has 2 Comments

Leave a Reply