Scala – Var,Args

  • date 25th May, 2021 |
  • by Prwatech |
  • 0 Comments

Understanding the VarArgs in Scala

 

Var-Args Functions(Methods) implies taking Variable Number of Arguments. As a Java Developer, We have effectively tasted use of Var-Args strategies in Java-based Applications.

Like Java, Scala likewise upholds "Variable Number Of Arguments" to Functions(Methods). Scala adheres to same guidelines like Java's Var-Args Methods with some language structure changes.

In Scala, VarArgs (variable-length arguments) provide a convenient way to define functions that accept a variable number of arguments of the same type. VarArgs allow functions to be with any number of arguments, including none, making them flexible and versatile.

To declare a VarArgs parameter in Scala, use the syntax args: Type*, where Type is the type of the arguments accept. Within the function body, args behaves like a sequence (Seq) of elements of type Type, allowing you to iterate over the arguments using standard collection operations.

When invoking a function with VarArgs, you can pass zero or more arguments of the specifiey type, which will be automatically wrapp into a sequence by the Scala compiler. For example, a function sum(numbers: Int*) can be with sum(1, 2, 3) to calculate the sum of the provid integers.

Under the hood, VarArgs are implemented using arrays (Array) in Scala, providing efficient performance for functions with a varying number of arguments.Understanding the VarArgs in Scala

use case 1:

// Scala program of varargs
object prwatech {
  // Driver code
    def main(args: Array[String])
    { 
              
        // Calling the function 
        println("Sum is: " + sum(2, 3, 100, 200, 30)); 
    } 
      
      
    // declaration and definition of function 
    def sum(a :Int, b :Int, args: Int *) : Int =
    {
        var result = a + b
      
        for(arg <- args)
        {
            result += arg
        }
      
        return result
    }
}

output:

Sum is: 335

use case 2:

// Scala program of varargs
object prwatech {
 // Driver code
    def main(args: Array[String]) 
    {
      
        // calling of function     
        printPrwa("Prwatech", "Data", "Science")
  
    }
  
    // declaration and definition of function
    def printPrwa(strings: String*) 
    {
        strings.map(println)
    }
}

output:

Prwatech
Data
Science

use case 3:

object prwatech {
def main(args: Array[String]) {
      printStrings("Hello", "Scala", "Python");
   }
   
   def printStrings( args:String* ) = {
      var i : Int = 0;
      
      for( arg <- args ){
         println("Arg value[" + i + "] = " + arg );
         i = i + 1;
      }
   }
}

output:

Arg value[0] = Hello
Arg value[1] = Scala
Arg value[2] = Python

Quick Support

image image