Default & named arguments in Scala
Parameters that carry defaults, and calls that name their arguments instead of ordering them.
// A parameter with a default may be left out by the caller.
def ticketLine(film: String, seats: Int = 1, matinee: Boolean = false) =
val each = if matinee then 8.5 else 12.0
f"$film%-12s $seats seat(s) ${each * seats}%6.2f"
// A default is evaluated only when the argument is left out.
def refund(paid: Double, fee: Double = 1.5): Double = paid - fee
def boxOffice(): Unit =
// Omitted parameters fall back to their defaults.
println(ticketLine("Nosferatu"))
// Named arguments may be written in any order.
println(ticketLine(seats = 3, film = "Solaris"))
// Positional first, then named to skip a middle parameter.
println(ticketLine("Stalker", matinee = true))
println(refund(24.0))
println(refund(24.0, fee = 0.0))
How it works
def ticketLine(film: String, seats: Int = 1, matinee: Boolean = false)gives two of its three parameters defaults.ticketLine("Nosferatu")leans on both defaults, whileticketLine(seats = 3, film = "Solaris")names its arguments and reverses their order.ticketLine("Stalker", matinee = true)passes one argument by position and names the last to skip overseats.
Keywords and builtins used here
BooleanDoubleIntStringUnitboxOfficedefelseifrefundthenticketLineval
The run, in numbers
- Lines
- 17
- Characters to type
- 720
- Tokens
- 123
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 98 seconds.
Step 2 of 3 in Functions, step 8 of 27 in Language basics.