Scala - Functions with Named Arguments
This chapter takes you through the concept of named arguments in Scala programming. You can specify the value of each parameter by name, rather than by position. So, it provides code readability and flexibility when calling functions.
Named Arguments
You can pass arguments to a function using the names of the parameters rather than their position in the parameter list. So, the function calls are clearer and reduce the risk of errors when working with multiple parameters and default values.
Named arguments provide a way to explicitly state which value is assigned to which parameter, making the function calls more readable and less error-prone.
Syntax
The syntax of the named argument in function call -
def functionName(param1: DataType, param2: DataType): ReturnType = {
// function body
}
// Calling the function with named arguments
functionName(param1 = value1, param2 = value2)
Example
The following example demonstrates defining and using a function with named arguments -
object Demo {
def printPersonInfo(name: String, age: Int, city: String): Unit = {
println(s"Name: $name, Age: $age, City: $city")
}
def main(args: Array[String]): Unit = {
// Using named arguments
printPersonInfo(name = "Alice", age = 30, city = "New York")
// Arguments can be in any order
printPersonInfo(city = "Los Angeles", name = "Bob", age = 25)
}
}
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Name: Alice, Age: 30, City: New York Name: Bob, Age: 25, City: Los Angeles
In the example, the printPersonInfo function takes three parameters: name, age, and city. The function is called using named arguments. So there is flexibility in the order of arguments, you put these arguments in any order in function calls because of named arguments. The function prints the information in formatted string.
Benefits of Named Arguments
Named arguments show which values are being passed to which parameters. So it enhances code readability when working with functions that have many parameters and parameters with similar types.
You can also change the order of parameters in the function call. So you can highlight parameters and when some parameters have default values. So, it provides code flexibility.
Example
The following example demonstrates the flexibility of named arguments.
def createUser(name: String, age: Int, email: String): Unit = {
println(s"Name: $name")
println(s"Age: $age")
println(s"Email: $email")
}
object Demo {
def main(args: Array[String]) = {
createUser(name = "Alice", age = 25, email = "alice@example.com")
createUser(email = "bob@example.com", name = "Bob", age = 30) // Changing the order
}
}
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Name: Alice Age: 25 Email: alice@example.com Name: Bob Age: 30 Email: bob@example.com
In the example, the createUser function takes three parameters: name, age, and email. We call this function using named arguments. So you can change the order of parameters with clarity.
Named Arguments with Default Values
You can ignore those arguments that have default values of parameters in the method. Because it is not mandatory to use them. The function will use the default values for the omitted arguments. However, you can also give values in named arguments if you need.
Syntax
The syntax of the named arguments with default values -
def functionName(param1: Type1 = defaultValue1, param2: Type2 = defaultValue2): ReturnType = {
// Function body
}
// Calling the function with named arguments and default values
functionName(param1 = value1) // param2 will use defaultValue2
Example
The following example shows the use of named arguments with default values in Scala programming -
def greet(name: String, greeting: String = "Hello"): Unit = {
println(s"$greeting, $name!")
}
object Demo {
def main(args: Array[String]) = {
greet(name = "Alice")
greet(name = "Bob", greeting = "Hi")
}
}
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Hello, Alice! Hi, Bob!
In the example, the greet function has default value for the greeting parameter. When calling the function. You can ignore the greeting argument. So the function will use default value "Hello". It overrides the default value when the greeting argument is provided.
Mixed Arguments
You can mix positional and named arguments in a single function call. However, all positional arguments must appear before any named arguments.
Syntax
The syntax of positional and named arguments -
def functionName(param1: Type1, param2: Type2): ReturnType = {
// Function body
}
// Calling the function with mixed arguments
functionName(value1, param2 = value2, ...)
Example
The following example shows the use of mixed arguments in Scala programming -
def printDimensions(length: Int, width: Int, unit: String = "cm"): Unit = {
println(s"Length: $length $unit")
println(s"Width: $width $unit")
}
object Demo {
def main(args: Array[String]) = {
printDimensions(10, 5)
printDimensions(20, width = 15, unit = "meters")
}
}
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Length: 10 cm Width: 5 cm Length: 20 meters Width: 15 meters
In the example, the printDimensions function takes two positional parameters: length and width. It also has one named parameter: unit, with a default value. You can use both positional and named arguments when calling the function. The positional arguments (length and width) come first. Then the named argument (unit).
Named Arguments in Higher-Order Functions
You can use named arguments in higher-order functions, where functions are passed as arguments and returned as results.
Example
The syntax of the named arguments in higher order function is -
def operateOnNumbers(a: Int, b: Int, operation: (Int, Int) => Int): Int = {
operation(a, b)
}
object Demo {
def main(args: Array[String]): Unit = {
// Using named arguments in a higher-order function
val sum = operateOnNumbers(a = 5, b = 10, operation = (x, y) => x + y)
val product = operateOnNumbers(a = 5, b = 10, operation = (x, y) => x * y)
println(s"Sum: $sum, Product: $product")
}
}
Save the above program in Demo.scala. Use the following commands to compile and execute this program.
Command
> scalac Demo.scala > scala Demo
Output
Sum: 15, Product: 50
In this example, the operateOnNumbers function takes two integers and operation function as parameters. Named arguments are used to pass values to a, b, and operation. So the function call is more expressive.
Function with Names Arguments Summary
- You can specify the names of parameters when calling a function.
- You can change the order of parameters in the function call. So, it improves the clarity and focus on important parameters.
- You can mix positional and named arguments in a single function call. But positional arguments must appear before named arguments.
- Named arguments are used in functions with multiple parameters or default values. So it reduces the risk of errors.
- You can use named arguments in Higher-order functions for better readability.