Scala function-variable argument


Release date:2023-11-15 Update date:2023-11-15 Editor:admin View counts:239

Label:

Scala function-variable argument

Scala allows you to specify that the last argument to the function can be duplicated, that is, we do not need to specify the number of arguments to the function, we can pass a variable length argument list to the function.

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

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

Execute the above code, and the output is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).