Previous

Next

Tour of Scala

Named Arguments

When calling methods, you can label the arguments with their parameter names like so:

In [1]:
def printName(first: String, last: String): Unit = {
  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"
John Smith
John Smith
John Smith
Out[1]:
defined function printName

Notice how the order of named arguments can be rearranged. However, 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 [2]:
printName(last = "Smith", "john") // error: positional after named argument
cmd1.sc:1: positional after named argument.
val res1 = printName(last = "Smith", "john") // error: positional after named argument
                                     ^Compilation Failed
Compilation Failed

Note that named arguments do not work with calls to Java methods.

Previous

Next

Tour of Scala