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.

You just need to remember few important observations.


The variable argument must be the last argument

So, the following code is invalid.

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: