In Scala, Repeated Method parameters are supported, which is helpful when we don’t know the number of arguments a method requires. This property of Scala is utilized in passing limitless parameters to a method defined.
Important points :
- The methods with Repeated Parameters should have each of the parameters of same type.
- A Repeated parameter is always the last parameter of the method defined.
- The method defined by us, can have only one parameter as Repeated Parameters.
Example:
object repeated
{
def main(args : Array[String])
{
def add(x : Int*)
: Int =
{
x.fold( 0 )( _ + _ )
}
println(add( 2 , 3 , 5 , 9 , 6 , 10 , 11 , 12 ))
}
}
|
In order to add any number of extra parameters, we need to put * mark after the type of the parameter being used.
Some more examples of Repeated Parameters:
- An Array can be passed in the Repeated Parameter method.
Example:
object arr
{
def main(args : Array[String])
{
def mul(x : Int*)
: Int =
{
x.product
}
println(mul(Array( 7 , 3 , 2 , 10 ) : _ *))
}
}
|
In order to pass an array in the defined method, we need to put a colon i.e, : and _* mark after passing the values in the array.
- An example to show that Repeated Parameters are always the last parameter of the method defined.
Example:
object str
{
def main(args : Array[String])
{
def show(x : String, y : Any*) =
{
"%s is a %s" .format(x, y.mkString( "_" ))
}
println(show( "GeeksforGeeks" , "Computer" ,
"Sciecne" , "Portal" ))
}
}
|
Output:
GeeksforGeeks is a Computer_Sciecne_Portal
Here, format is used to format strings.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
29 Mar, 2019
Like Article
Save Article