Repeating Parameters Scala allows you to specify that the last parameter can be repeated (variable-length arguments) when defining a function, allowing the function caller to invoke the function using a variable-length argument list, using "*" in Scala to indicate that the parameter is a repeating parameter. For example:
Scala> def Echo (args:string *) = | for (Arg <-args) println (ARG) echo: (args:string*) unitscala> Echo () scala> Echo ("one") onescala> Echo ("Hello "," "World") HelloWorld
Inside the function, the type of the variable length parameter is actually an array, such as the String * type of the example above is actually array[string]. However, now that you are trying to pass an array-type parameter directly to this parameter, the compiler will give an error:
Scala> Val arr= Array ("What's", "Up", "Doc?") Arr:array[string] = Array (what's, up, Doc?) Scala> Echo (arr) <console>:10:error:type mismatch; Found : array[string] required:string Echo (arr) ^
To avoid this, you can solve this by adding a _* to the variable, which tells the Scala compiler to pass in each element of the array one at a time, instead of the array as a whole.
Scala> Echo (arr: _*) What ' Supdoc?
named arguments typically, when a function is called, the parameter is passed in and the function definition is corresponding to the argument list one by one.
scala> def Speed (Distance:float, time:float): Float = distance/timespeed: (distance:float, Time:float) Floatscala> speed (100,10) res0:float = 10.0
Using named parameters allows you to pass in arguments in any order, such as the following call:
Scala> speed (time=10,distance=100) res1:float = 10.0scala> speed (distance=100,time=10) res2:float = 10.0
Default parameter values When you define a function, Scala allows you to specify the default value of the parameter, allowing the function to be called without indicating the parameter, at which point the parameter uses the default value. The default parameters are usually used with named parameters, for example:
Scala> def printtime (out:java.io.PrintStream = console.out, divisor:int =1) = | out.println ("time =" + system.cur Renttimemillis ()/divisor) Printtime: (Out:java.io.PrintStream, Divisor:int) unitscala> printtime () time = 1383220409463scala> Printtime (divisor=1000) time = 1383220422
Scala variable parameter list, named parameters and parameter defaults