Tuesday 1 September 2020

Scala: Varargs: Variable number of arguments

A function can take variable number of arguments. Variable number of arguments are represented with * after the type.

For example,

def concat(separator: String, messages: String*) : String = {
     var result = ""
     for (data <- messages) {
     result += data + separator
     }
     result
}

Above function takes a separator and messages as arguments and combines the messages using given separator.

 

concat(",", "One", "Two", "Three")

Above statement return the string "One,Two,Three,"

scala> def concat(separator: String, messages: String*) : String = {
     |   var result = ""
     |   for (data <- messages) {
     |     result += data + separator
     |   }
     |   result
     | }
def concat(separator: String, messages: String*): String

scala> concat(",", "One", "Two", "Three")
val res87: String = One,Two,Three,

scala> concat(">>>", "One", "Two", "Three")
val res88: String = One>>>Two>>>Three>>>

Example: Find the multiplication of given integers.

scala> def mul(elements : Int*) : Int = {
     |   var result = 1
     |   
     |   for (ele <- elements){
     |     result *= ele
     |   }
     | 
     |   result
     | }
def mul(elements: Int*): Int

scala> mul(2,3,5,7)
val res89: Int = 210

Can I pass a range to ‘mul’ function?

Yes.

 

mul(1 to 5 : _*)

Above snippet calculate the multiplication of numbers from 1 to 5.

scala> mul(1 to 5 : _*)
val res92: Int = 120

scala> mul(1 to 10 : _*)
val res91: Int = 3628800

‘-*’ notation is helpful while computing the result recursively.

def mulRecursive(elements : Int*) : Int = {
     if(elements.length == 0)
          1
     else
          elements.head * mulRecursive(elements.tail : _*)
}

'mulRecursive' function takes a variable number of integers as arguments and returns multiplication of numbers. As you see the result, I am taking the first value and calling the function with tail data recursively until the tail is empty.

scala> def mulRecursive(elements : Int*) : Int = {
     |    if(elements.length == 0)
     |      1
     |    else
     |      elements.head * mulRecursive(elements.tail : _*)
     | }
def mulRecursive(elements: Int*): Int

scala> 

scala> mulRecursive(1, 2, 3, 4, 5)
val res93: Int = 120

scala> mulRecursive(1 to 5 : _*)
val res94: Int = 120



Previous                                                    Next                                                    Home

No comments:

Post a Comment