Home »
Scala
Functions with named arguments in Scala
By IncludeHelp Last updated : October 20, 2024
Functions with named arguments
A function is Scala can take multiple arguments. These arguments are traditionally called in sequence while calling a function. But in Scala programming, the program is given the power to alter the traditional sequence of arguments. Scala provides its users named arguments these are used to change the order of using arguments at call.
Suppose a function that has two variables var1 and var2. If we want to initialize var2 first then the following syntax is used.
Syntax
functionName ( var2 = value2, var2 = value1 );
Explanation
This will pass the value2 to the second argument in the list. And value1 in the first argument in the list.
Example of functions with named arguments
object Demo {
def sub( a:Int, b:Int ) = {
println("Substraction = " + (a-b) );
}
def main(args: Array[String]) {
println("The fucntion is called using named function call")
sub(b = 5, a = 7);
}
}
Output
The fucntion is called using named function call
Substraction = 2
Explanation
This code displays how to use named arguments in Scala? The code initializes a function named sub(), it expects two arguments and substracts second from first. At function call, the arguments are filled using the names that initialize them in the order the programmer wants.