TExcelTAD
Home › Scala › Scala Default & Named Parameters

Scala Default & Named Parameters

Scala methods can give parameters default values and let callers pass arguments by name. Together these two features replace most of the method overloading and "builder" boilerplate you might know from Java.

Default values

Write = value after a parameter's type. Callers may then leave that argument out.

scala · try it yourself
def greet(name: String, greeting: String = "Hello", punctuation: String = "!"): String =
  s"$greeting, $name$punctuation"

@main def run(): Unit =
  println(greet("Sam"))
  println(greet("Sam", "Welcome"))
  println(greet("Sam", "Hi", "?"))
Hello, Sam!
Welcome, Sam!
Hi, Sam?

Default expressions are evaluated each time the method is called without that argument, and they may refer to earlier parameters:

scala · try it yourself
def range(start: Int, end: Int, step: Int = 1, label: String = ""): String =
  val tag = if label.isEmpty then s"$start..$end" else label
  s"$tag: ${(start to end by step).mkString(",")}"

def box(width: Int, height: Int = 0): String =
  val h = if height == 0 then width else height
  s"${width}x$h"

@main def run(): Unit =
  println(range(1, 9, 2))
  println(box(4))
  println(box(4, 2))
1..9: 1,3,5,7,9
4x4
4x2

Named arguments

Any argument can be passed as name = value. This makes calls self-documenting and lets you skip some defaults while setting later ones.

scala · try it yourself
def createUser(name: String, admin: Boolean = false, active: Boolean = true, theme: String = "light"): String =
  s"$name(admin=$admin, active=$active, theme=$theme)"

@main def run(): Unit =
  println(createUser("ana"))
  println(createUser("ben", theme = "dark"))
  println(createUser(active = false, name = "cy"))
  println(createUser("dee", admin = true, theme = "solarized"))
ana(admin=false, active=true, theme=light)
ben(admin=false, active=true, theme=dark)
cy(admin=false, active=false, theme=light)
dee(admin=true, active=true, theme=solarized)

Tip: Always name Boolean arguments. createUser("ben", true, false) hides its meaning; createUser("ben", admin = true, active = false) does not.

Rules to remember

Rule Example
Positional arguments must come before named ones f(1, b = 2) ✔, f(a = 1, 2) only if 2 is in the right position
Named arguments may be in any order createUser(theme = "dark", name = "x")
A parameter without a default must always be given createUser() does not compile
Default values also work for constructors class Config(port: Int = 8080)

Defaults in constructors and case classes

Constructors are just special methods, so the same features apply. Combined with case classes, defaults give you a lightweight "options" object.

scala · try it yourself
case class HttpOptions(
    timeoutMs: Int = 5000,
    retries: Int = 3,
    followRedirects: Boolean = true,
    userAgent: String = "scala-client"
)

@main def run(): Unit =
  val default = HttpOptions()
  val fast = HttpOptions(timeoutMs = 500, retries = 0)
  println(default)
  println(fast)
  println(fast.copy(userAgent = "bot/1.0"))
HttpOptions(5000,3,true,scala-client)
HttpOptions(500,0,true,scala-client)
HttpOptions(500,0,true,bot/1.0)

copy uses named arguments too: it creates a new instance with only the named fields changed.

Multiple parameter lists

A method may have more than one parameter list. This is used for currying, for passing a block of code as the last argument, and for using parameters (see Givens & Using).

scala · try it yourself
def repeat(times: Int)(action: Int => Unit): Unit =
  for i <- 1 to times do action(i)

def tax(rate: Double)(amount: Double): Double = amount * rate

@main def run(): Unit =
  repeat(3) { i =>
    println(s"step $i")
  }
  val vat = tax(0.2)
  println(vat(150.0))
step 1
step 2
step 3
30.0

tax(0.2) supplies only the first list; the result is a function waiting for amount.

By-name parameters

A parameter of type => T is evaluated only when it is used, and again each time it is used. This lets you write methods that behave like built-in control structures.

scala · try it yourself
def logIf(enabled: Boolean)(message: => String): Unit =
  if enabled then println(message)

def expensive(): String =
  println("(computing message)")
  "details"

@main def run(): Unit =
  logIf(false)(expensive())
  logIf(true)(expensive())
(computing message)
details

With enabled = false the message expression was never evaluated.

Test yourself

Given def f(a: Int, b: Int = 2, c: Int = 3), which call sets only c to 9?

  1. f(1, 9)
  2. f(1, c = 9)
  3. f(c = 9)
  4. f(1, , 9)

What does copy(retries = 0) on a case class instance do?

  1. Changes the original object
  2. Returns a new instance with retries replaced
  3. Copies to the clipboard
  4. Throws because the class is immutable

When is a by-name parameter msg: => String evaluated?

  1. Before the method is called
  2. Only when (and each time) the method uses it
  3. Exactly once at compile time
  4. Never