Scala – Var,Args

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

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.

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
0
0

Quick Support

image image