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.

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:

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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.