Home > Articles > Programming

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

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", "[", "]<<<")
  • + Share This
  • 🔖 Save To Your Account