Scala varargs (Scala varargs)
Varargs is the concept of providing a variable-length argument to a function. Scala programming language also provides this functionality in its programs.
Varargs是为函数提供变长参数的概念。 Scala编程语言还在其程序中提供了此功能。
In Scala, the last argument of the method can be of variable argument i.e. it can be repeated the multiple numbers of times in the parameter list of the method. In this function, the programmer can pass multiple arguments.
在Scala中,方法的最后一个参数可以是可变参数,即可以在方法的参数列表中重复多次。 在此函数中,程序员可以传递多个参数。
The varargs are stored as an array of the same data type i.e. array [data_type]. For example, if you use float as the data type of varargs, they are stored as array [float].
可变参数存储为具有相同数据类型的数组,即数组[data_type] 。 例如,如果使用float作为varargs的数据类型,则它们将存储为数组[float] 。
To make a method accept varargs, you need to place an asterisk (*) at last argument which will be made of variable length i.e. varargs.
为了使方法接受varargs,您需要在最后一个参数处加一个星号( * ),该参数将由可变长度(即varargs)组成 。
Syntax:
句法:
def method_name (valarg_name : data_tpye *) : Int = { code }
Varargs are good to go when you do not know the number of arguments that a method will accept.
当您不知道某个方法将接受的参数数量时,最好使用Varargs 。
Example 1:
范例1:
object MyObject
{
def stringreturn(strings: String*)
{
strings.map(print)
}
def main(args: Array[String])
{
stringreturn("Hello! ", "Welcome ", "To ", "Include Help")
}
}
Output
输出量
Hello! Welcome To Include Help
Example 2:
范例2:
object MyObject
{
def avg(a: Int *) : Double =
{
var result = 0
var count = 0
for(arg <- a)
{
result += arg
count+= 1
}
return result/count
}
def main(args: Array[String])
{
println("The average is: " + avg(543, 98, 123, 25, 323));
}
}
Output
输出量
The average is: 222.0