Open In App

Scala | Repeated Method Parameters

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 :

Example:




// Scala program of repeated 
// parameters
  
// Creating object
object repeated
{
  
    // Main method
    def main(args: Array[String])
    {
  
        // Creating a method with
        // repeated parameters
        def add(x: Int*)
        : Int =
        {
  
            // Applying 'fold' method to 
            // perform binary operation
            x.fold(0)(_+_)
      
        }
  
        // Displays Addition
        println(add(2, 3, 5, 9, 6, 10, 11, 12))
    }
}

Output:

58

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:


Article Tags :