Default values and named arguments


Devault values and named arguments are two different features of Scala programming language. However, they make more sense when used together. Let's start by creating a Scala function, and we will use this function to understand the notion of named arguments.
So, here is a simple example.

The above function takes two parameters. The first parameter is a function value and the second parameter should be a string value. The example above also shows a sample usage and the output. Whenever you want to call the above function, the first parameter must always be a function value and the second one should be a string. You cannot break this rule. If you try to change the order of the parameters, I mean, pass string first and the function value second, You will get an error.


The Named Argument is the rescue to this limitation. It allows us to pass the input parameters in whatever order we prefer. The example below gives you an idea of the syntax.

The name of the string parameter is s. I gave that name at the time of function definition. Similarly, the name of the function parameter is f. Instead of passing the parameters in the specified order, we can tell Scala about both of the things, the name and the value of the parameter. Irrespective of the order, the name allows the Scala compiler to map the parameter values correctly.
However, you might be wondering that why would you want to pass parameters in a different order. There must be some reason. Isn't it?
Changing order of function parameter starts making sense as soon as you give a default value for an argument. Here is the example .

We can assign a default value for a parameter using an = symbol. The above example assigns a default value for the first parameter. If the function caller does not pass any value for the first parameter, Scala will assume the default value.
Now, if I want to skip the first parameter and supply only the second parameter, I will get an error a "Not enough arguments." There comes the named argument.

Use a named argument, and you can skip the first parameter because It has a default value.
So, to make some parameters optional, we use the default value, and when we want to skip the default value parameters in a function call, we use named argument syntax to pass the remaining arguments.


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: