top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to use Named Parameters in Scala? What is the use of Named Parameters in Scala?

+1 vote
421 views
How to use Named Parameters in Scala? What is the use of Named Parameters in Scala?
posted Aug 11, 2016 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

When calling methods and functions, you can use the name of the variables explicitly in the call, like so:

  def printName(first:String, last:String) = {
    println(first + " " + last)
  }
  printName("John","Smith")
  // Prints "John Smith"
  printName(first = "John",last = "Smith")
  // Prints "John Smith"
  printName(last = "Smith",first = "John")
  // Prints "John Smith"

Note that once you are using parameter names in your calls, the order doesn’t matter, so long as all parameters are named. This feature works well with default parameter values:

  def printName(first:String = "John", last:String = "Smith") = {
    println(first + " " + last)
  }
  printName(last = "Jones")
  // Prints "John Jones"

Since you can place the parameters in any order you like, you can use the default value for parameters that come first in the parameter list.

answer Sep 15, 2016 by Dominic
Similar Questions
+2 votes

How to define Default parameters in Scala? What is the use of Default Parameters in Scala? How to avoid implementing Auxiliary Constructors or Multiple Constructors in Scala?

+4 votes

What is the main use of Option and Either in Scala? How do we handle Errors or Exceptions in Functional Style(FP style) in Scala?

...