top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is Var-Args Parameters to function/method in Scala?

+2 votes
396 views

What is Var-Args Parameters to function/method in Scala? What is the difference between Scala’s Var-Args and Java’s Var-Args?

posted Aug 2, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
 
Best answer

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.

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
answer Sep 19, 2016 by Dominic
Similar Questions
+2 votes

How to define Default parameters in Scala? What is the use of Default Parameters in Scala? How to avoid implementing Auxiliary Constructors or Multiple Constructors in Scala?

...