Home » Scala language

Functions with named arguments in Scala

In Scala programming, there are named arguments in Scala. These named arguments are used to alter the order of passing arguments in functions of Scala. In this tutorial, you will learn how to pass named arguments in Scala?
Submitted by Shivang Yadav, on June 28, 2019

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.


    functionName ( var2 = value2, var2 = value1 );


This will pass the value2 to the second argument in the list. And value1 in the first argument in the list.


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);


The fucntion is called using named function call
Substraction = 2


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.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.