Home » Scala language

Varargs in Scala

Scala varargs: The concept of providing variable-length argument to a method. In this tutorial on varargs in Scala, we will learn about varargs, examples, and programs related to it.
Submitted by Shivang Yadav, on September 22, 2019

Scala varargs

Varargs is the concept of providing a variable-length argument to a function. Scala programming language also provides this functionality in its programs.

In Scala, the last argument of the method can be of variable argument i.e. it can be repeated the multiple numbers of times in the parameter list of the method. In this function, the programmer can pass multiple arguments.

The varargs are stored as an array of the same data type i.e. array [data_type]. For example, if you use float as the data type of varargs, they are stored as array [float].

To make a method accept varargs, you need to place an asterisk (*) at last argument which will be made of variable length i.e. varargs.

Syntax:

    def method_name (valarg_name : data_tpye *) : Int = { code }

Varargs are good to go when you do not know the number of arguments that a method will accept.

Example 1:

object MyObject 
{ 
    def stringreturn(strings: String*) 
    { 
        strings.map(print) 
    }
    
    def main(args: Array[String]) 
    { 
        stringreturn("Hello! ", "Welcome ", "To ", "Include Help") 
    } 
} 

Output

Hello! Welcome To Include Help

Example 2:

object MyObject 
{ 
    def avg(a: Int *) : Double =
    { 
        var result = 0 
        var count = 0
        
        for(arg <- a) 
        { 
            result += arg 
            count+= 1
        } 
        return result/count 
    }
    
    def main(args: Array[String]) 
    { 
        println("The average is: " + avg(543, 98, 123, 25, 323)); 
    } 
}

Output

The average is: 222.0



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.