Variable Length Arguments

Most of the programming languages support the notion of variable length argument. Scala is not an exception. It allows you to indicate that the last argument of a function is a variable length argument. So it may be repeated multiple times.
Here is an example.

    def echo(s:String*) = s foreach println
    //You can use it like this.
    //You can pass as many arguments as you want.
    echo("One","Two","Three", "Four", "Five") 
    //Even no arguments is fine

You just need to remember few important observations.

The variable argument must be the last argument

So, the following code is invalid.

    def echo(s:String*, i:Int) = s foreach println                 

All of the variable argument values are of the same data type

If the variable argument is of type Int, you can pass n number of Integers. However, you cannot mix in a string with them.

The variable argument is available to the function body as an array

In the above example, s is available to the function body as a string array. Since the type of s is a String, inside the body, s is an array of string. If we change the type of s to an Int, inside the body, s would be available as an array of Int.

Read More

Basics of Scala functions | Function Literals in Scala | Function values | Local Functions | Variable length argument | Default values and named arguments | Scala Placeholder syntax | Higher Order functions | Partially applied functions | Function currying

By Prashant Pandey -

You will also like:

Kafka Core Concepts

Learn Apache Kafka core concepts and build a solid foundation on Apache Kafka.

Learning Journal

Hadoop Security

Hadoop security implementation using Kerberos.

Learning Journal

Free virtual machines

Get upto six free VMs in Google Cloud and learn Bigdata.

Learning Journal

Lazy Evaluations

Evaluate the expression now vs evaluate it for the first use. Strict vs Lazy?

Learning Journal

Scala named arguments

Learn about named arguments and default values in Scala functions with examples.

Learning Journal