- 2.1 Conditional Expressions
- 2.2 Statement Termination
- 2.3 Block Expressions and Assignments
- 2.4 Input and Output
- 2.5 Loops
- 2.6 Advanced for Loops and for Comprehensions
- 2.7 Functions
- 2.8 Default and Named Arguments L1
- 2.9 Variable Arguments L1
- 2.10 Procedures
- 2.11 Lazy Values L1
- 2.12 Exceptions
- Exercises
2.9 Variable Arguments L1
Sometimes, it is convenient to implement a function that can take a variable number of arguments. The following example shows the syntax:
def sum(args: Int*) = { var result = 0 for (arg <- args) result += arg result }
You can call this function with as many arguments as you like.
val s = sum(1, 4, 9, 16, 25)
The function receives a single parameter of type Seq, which we will discuss in Chapter 13. For now, all you need to know is that you can use a for loop to visit each element.
If you already have a sequence of values, you cannot pass it directly to such a function. For example, the following is not correct:
val s = sum(1 to 5) // Error
If the sum function is called with one argument, that must be a single integer, not a range of integers. The remedy is to tell the compiler that you want the parameter to be considered an argument sequence. Append : _*, like this:
val s = sum(1 to 5: _*) // Consider 1 to 5 as an argument sequence
This call syntax is needed in a recursive definition:
def recursiveSum(args: Int*) : Int = { if (args.length == 0) 0 else args.head + recursiveSum(args.tail : _*) }
Here, the head of a sequence is its initial element, and tail is a sequence of all other elements. That’s again a Seq, and we have to use : _* to convert it to an argument sequence.