Named parameters in Scala

Named Parameters

When calling methods, we can label the arguments with their parameter names.

Let us have a look into the below code:

package com.scala.test

object TestNamed {
def dummy (a:String, b:String) = {
println(a+b)
}
def main(args: Array[String]) {
dummy(“test”,”named”)
dummy(a=”test”,b=”named”)
dummy(b=”test”,a=”named”)
dummy(“test”,b=”named”)
dummy(a=”test”,”named”)
}
}

Output
testnamed
testnamed
namedtest
testnamed
testnamed

Notes:

#1. If some arguments are named and others are not, the unnamed arguments must come first and in the order of their parameters in the method signature.
In the above example, the following method calls will not compile.
dummy(“test”,a=”named”) // invalid, parameter ’a’ specified twice
dummy(b=”test”,”named”) // invalid, a positional after named argument

#2. Named arguments do not work with calls to Java methods.

Leave a Reply

Your email address will not be published. Required fields are marked *