- 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.8 Default and Named Arguments L1
You can provide default arguments for functions that are used when you don’t specify explicit values. For example,
def decorate(str: String, left: String = "[", right: String = "]") = left + str + right
This function has two parameters, left and right, with default arguments "[" and "]".
If you call decorate("Hello"), you get "[Hello]". If you don’t like the defaults, supply your own: decorate("Hello", "<<<", ">>>").
If you supply fewer arguments than there are parameters, the defaults are applied from the end. For example, decorate("Hello", ">>>[") uses the default value of the right parameter, yielding ">>>[Hello]".
You can also specify the parameter names when you supply the arguments. For example,
decorate(left = "<<<", str = "Hello", right = ">>>")
The result is "<<<Hello>>>". Note that the named arguments need not be in the same order as the parameters.
Named arguments can make a function call more readable. They are also useful if a function has many default parameters.
You can mix unnamed and named arguments, provided the unnamed ones come first:
decorate("Hello", right = "]<<<") // Calls decorate("Hello", "[", "]<<<")