🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Default and Named Arguments

A default value is a value a parameter uses when the call leaves that argument out. Named arguments let a call state which parameter each value is for.

The default fills a skipped argument

The name parameter has the default "friend". The first call passes nothing, so the default is used.

def welcome(name: String = "friend"): Unit =
  println("Hello, " + name)

@main def main(): Unit =
  welcome()
  welcome("Ana")

Skipping one argument at a time

Both parameters of ticket have defaults. Each call leaves out a different mix and still gets a complete result.

def ticket(row: String = "A", seat: Int = 1): String = row + seat

@main def main(): Unit =
  println(ticket())
  println(ticket("B"))
  println(ticket("C", 5))

Named arguments in another order

The first call names every argument and lists them in a different order than the definition. The names, not the positions, decide where each value goes.

def build(code: String, level: Int, room: Int): String = code + "-" + level + "-" + room

@main def main(): Unit =
  println(build(room = 12, code = "N", level = 3))
  println(build("S", 1, 7))

Example

def signup(name: String, plan: String = "free", months: Int = 1): String = name + " | " + plan + " | " + months

@main def main(): Unit =
  println(signup("Ana"))
  println(signup("Ben", months = 6))
  println(signup(months = 3, name = "Cid", plan = "pro"))

Key points

  • Default value: A parameter gets a default by writing an equals sign and a value after its type.
  • Skipping: A call can leave out any argument whose parameter has a default.
  • Overriding: Passing an argument replaces the default for that call only.
  • Named argument: A call can write the parameter name, an equals sign, and the value.
  • Any order: Named arguments can be written in a different order than the parameters.

In this example, signup has one required parameter and two parameters with defaults. The first call passes only a name, so plan and months use their defaults. The second call names months to skip plan, and the third call names all three arguments in a new order.

Note

Arguments without names still fill the parameters from the left, in order.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

With def welcome(name: String = "friend"): Unit printing "Hello, " plus the name, what does welcome() print?