Default and Named Arguments

Default and Named Arguments in Kotlin: --- At the back of an ironmonger's shop stands a paint-mixing counter with a shelf of base tins and a rack of colorant…


The Analogy: The Paint-Mixing Counter and the Tint Recipe Card

At the back of an ironmonger's shop stands a paint-mixing counter with a shelf of base tins and a rack of colorant bottles. Behind the counter hangs the recipe card: a printed sheet with a line for the base, a line for the number of litres, a line for the sheen, and a line for each colorant, every line carrying a standard value in the margin. A customer who asks for "a tin of white" gets exactly what the card's standard values describe -- one litre, matte finish, no tint. The standard values in the margin are the default arguments: what the counter uses when the customer says nothing.

Most customers vary only one or two lines. A decorator wants the standard white but in a satin finish. He does not restate the base, the litres and every colorant; he names the one line he is changing -- "satin" -- and the rest stay at their margin values. That is a named argument: the customer points at a specific line by its label and gives it a value, leaving every unmentioned line on its standard. Because he names the line, he need not touch the lines above or below it, and the order in which he calls out his changes does not matter to the man mixing the tin.

The naming becomes essential the moment a customer wants to change a later line while leaving an earlier one standard. Suppose the litres line comes before the tint line, and the customer wants the standard single litre but with two parts of ochre. If he simply calls out numbers in order, the mixer cannot tell that the first number he hears is meant for tint and not for litres. So the customer must name the later line -- "tint, two parts" -- and the litres line quietly takes its standard value of one. You cannot skip a line by leaving a gap in a spoken list; you skip it by naming the line you actually mean.

The failure mode belongs to the shop that records everything by position and never by name. For years the recipe card listed base, litres, sheen, tint in that fixed order, and the counter hands took orders as four numbers in that sequence. Then head office reprints the card with a new "primer" line inserted after the base. Every old habit of calling four numbers in order now feeds the litres figure into the primer line, the sheen figure into litres, and so on down the card. Nothing errors -- each line receives a value of the right kind -- so a tin of standard green comes out as something else entirely, and the mistake is only caught when the colour dries wrong on the wall. Naming each line would have survived the reprint untouched.


Syntax or Core Structure

fun mixPaint(base: String, litres: Int = 1, sheen: String = "matte"): String =
    litres.toString() + "L " + base + " (" + sheen + ")"

fun main() {
    println(mixPaint("white"))
    println(mixPaint("white", 5))
    println(mixPaint("white", 5, "gloss"))
    println(mixPaint("white", sheen = "satin"))
    println(mixPaint(base = "navy", sheen = "eggshell"))
}

mixPaint declares litres and sheen with default values, so only base is required. The first call supplies just base and both defaults apply. The second overrides litres positionally and leaves sheen at its default. The third overrides both positionally. The fourth is the important one: it keeps litres at its default of 1 and overrides sheen by name -- there is no way to reach sheen positionally without also giving litres, so the name is what lets the middle parameter fall through to its default. The last call names everything and could list the names in any order.

Output:

1L white (matte)
5L white (matte)
5L white (gloss)
1L white (satin)
1L navy (eggshell)

Technical Depth: When Defaults Run and How Names Bind

A default expression runs per call, only when the argument is omitted

A default is not a constant baked in once. It is an expression evaluated afresh each time the function is called without that argument, and skipped entirely when the caller supplies one. That distinction is invisible for a literal like 1, but it matters the moment the default has a side effect or allocates.

var issued = 0
fun nextTicket(): Int { issued += 1; return issued }

fun order(colour: String, parts: Int = 1, id: Int = nextTicket()): String =
    "#" + id + " " + colour + " x" + parts

fun main() {
    println(order("red"))
    println(order("red", 3))
    println(order("red", 3, 99))
    println(order("blue"))
    println("tickets issued: " + issued)
}

Output:

#1 red x1
#2 red x3
#99 red x3
#3 blue x1
tickets issued: 3

The first call omits id, so nextTicket() runs and returns 1. The second omits it again and gets 2. The third supplies 99, so the default expression does not run at all and the counter stays at 2. The fourth omits it and gets 3. Four calls, but only three of them evaluated the default, which is exactly what issued reports. A default that allocated mutableListOf() would likewise hand back a distinct fresh list to every call that omitted it.

A default may also refer to parameters declared before it, which is how you express "same as width unless told otherwise":

fun box(width: Int, height: Int = width, depth: Int = width): Int =
    width * height * depth

fun main() {
    println("cube 3: " + box(3))
    println("slab: " + box(4, 1))
    println("named depth: " + box(2, depth = 5))
}

Output:

cube 3: 27
slab: 16
named depth: 20

box(3) fills both height and depth from width, giving 3 * 3 * 3. box(4, 1) sets height to 1 and lets depth default to width, giving 4 * 1 * 4. box(2, depth = 5) keeps height at the default width of 2 and names depth, giving 2 * 2 * 5. A default can reference earlier parameters but never later ones, because the later ones may not have been bound yet.

The rules that govern mixing positional and named

The table below fixes the five call forms and what each guarantees. Read the middle column as the rule and the right column as the consequence.

Call formThe rule it followsWhat results
all positionalarguments bind by their positiontrailing defaulted parameters may be dropped
all namedarguments bind by their labelthe labels may appear in any order
positional then namedpositional ones keep their own slotsrequired once a middle parameter is skipped
skip a middle defaultthe later argument must be namedthe skipped parameter takes its default
supply a defaulted argumentgive it in any legal formthat parameter's default expression never runs

Two subtleties sit behind that table. First, an overriding function is forbidden to declare its own default values -- it inherits them from the base declaration, and repeating them is a compile error. Second, when you call a method through a variable, the default value is chosen from the static (declared) type of that variable, even though the body that runs is chosen by the runtime type.

open class Sprayer {
    open fun coat(colour: String, coats: Int = 2): String = colour + " x" + coats
}
class FineSprayer : Sprayer() {
    override fun coat(colour: String, coats: Int): String = "fine " + colour + " x" + coats
}

fun main() {
    val s: Sprayer = FineSprayer()
    println(s.coat("teal"))
    println(s.coat("teal", 4))
}

Output:

fine teal x2
fine teal x4

FineSprayer.coat does not -- and may not -- restate the default. The call s.coat("teal") takes the default 2 from Sprayer, the declared type of s, then dispatches to FineSprayer's body, which prints the fine prefix. Body from the runtime type, default from the static type: two different questions with two different answers.


Real World Example: The Paint Counter Order Desk

The order desk prices tins from the recipe card. A tin costs BASE pence per litre, plus a per-litre sheen surcharge (matte adds nothing, satin adds 40, gloss adds 80), plus TINT_PER_PART pence per litre for each part of colorant. priceTin gives every optional line a default, so the plainest order names only its colour. The program prints a padded board, then shows that two of the rows can be reproduced by default and named calls.

const val BASE = 300
const val TINT_PER_PART = 15
const val MATTE = 0
const val SATIN = 40
const val GLOSS = 80
const val ORDERS = "white:1:matte:0,magnolia:5:matte:2,navy:3:gloss:4,sage:2:satin:0,crimson:10:matte:6"
const val W_NAME = 10
const val W_LITRES = 7
const val W_SHEEN = 7
const val W_TINT = 6
const val W_PRICE = 7

fun sheenSurcharge(sheen: String): Int = when (sheen) {
    "satin" -> SATIN
    "gloss" -> GLOSS
    else -> MATTE
}

fun priceTin(name: String, litres: Int = 1, sheen: String = "matte", tint: Int = 0): Int =
    litres * (BASE + sheenSurcharge(sheen) + tint * TINT_PER_PART)

fun row(name: String, litres: String, sheen: String, tint: String, price: String): String =
    name.padStart(W_NAME) + litres.padStart(W_LITRES) + sheen.padStart(W_SHEEN) +
        tint.padStart(W_TINT) + price.padStart(W_PRICE)

fun main() {
    val entries = ORDERS.split(",").map { it.split(":") }
    val ruleWidth = W_NAME + W_LITRES + W_SHEEN + W_TINT + W_PRICE
    println(row("NAME", "LITRES", "SHEEN", "TINT", "PRICE"))
    println("-".repeat(ruleWidth))

    var tLitres = 0
    var tTint = 0
    var tPrice = 0
    for (e in entries) {
        val name = e[0]
        val litres = e[1].toInt()
        val sheen = e[2]
        val tint = e[3].toInt()
        val price = priceTin(name, litres, sheen, tint)
        tLitres += litres; tTint += tint; tPrice += price
        println(row(name, litres.toString(), sheen, tint.toString(), price.toString()))
    }
    println("-".repeat(ruleWidth))
    println(row("TOTALS", tLitres.toString(), "--", tTint.toString(), tPrice.toString()))

    println("orders priced: " + entries.size)
    println("white via all defaults: " + priceTin("white"))
    println("magnolia via named tint: " + priceTin("magnolia", 5, tint = 2))
    println("board total " + tPrice + " = sum of rows " + tPrice +
        " agree: " + (tPrice == tPrice))
    println("gloss adds " + sheenSurcharge("gloss") + " but typo glos adds " +
        sheenSurcharge("glos"))
}

Output:

      NAME LITRES  SHEEN  TINT  PRICE
-------------------------------------
     white      1  matte     0    300
  magnolia      5  matte     2   1650
      navy      3  gloss     4   1320
      sage      2  satin     0    680
   crimson     10  matte     6   3900
-------------------------------------
    TOTALS     21     --    12   7850
orders priced: 5
white via all defaults: 300
magnolia via named tint: 1650
board total 7850 = sum of rows 7850 agree: true
gloss adds 80 but typo glos adds 0

Trace the navy row. Three litres, gloss sheen, four parts of tint. The per-litre cost is BASE + sheenSurcharge("gloss") + 4 * TINT_PER_PART, that is 300 + 80 + 60, or 440, and three litres come to 1320. The totals line sums the litres to 21, the tint parts to 12, and the prices to 7850, and the sheen column shows -- because a sum of finishes has no meaning.

The two lines below the board demonstrate the feature the topic is about. priceTin("white") supplies only the colour and leans on every default -- one litre, matte, no tint -- and reproduces the white row's 300 exactly. priceTin("magnolia", 5, tint = 2) skips the sheen parameter, letting it default to matte, and names tint to reach past it; the result matches the magnolia row's 1650. Both prove that the defaulted and named calls agree with the fully-specified rows in the loop.

The last two lines are where honesty is owed. The board total ... agree: true line is a pure tautology: it compares tPrice with tPrice, so it would print true no matter what priceTin computed, and it validates nothing at all. But the genuine design flaw is in sheenSurcharge. Its when ends in else -> MATTE, so any string that is not exactly "satin" or "gloss" is priced as matte and adds nothing. The final output line shows the trap directly: "gloss" adds 80, but the typo "glos" silently adds 0, producing a plausible, cheaper, wrong price with no error anywhere. Because sheen is a defaulted String rather than an enum, the compiler cannot catch the misspelling, and the board cannot reveal it because every sample uses a correctly-spelled finish. A narrower limit is the usual one: padStart never truncates, so the first colour longer than ten characters would push its row past the rule and misalign the board.


Common Mistakes

  1. Trying to skip a middle default with a positional call. You cannot leave a gap in a positional argument list. To keep litres at its default while setting sheen, you must write mixPaint("white", sheen = "satin"); there is no positional syntax that says "default here, value there."
  1. Placing a positional argument after a named one where the position no longer lines up. Kotlin allows a positional argument to follow a named one only when it still sits in its own correct slot. The safe habit is to name every argument once you have named any that precedes a skipped parameter, rather than reasoning about which mixed forms happen to be legal.
  1. Redeclaring a default value in an overriding function. An override inherits the base's defaults and is not permitted to state its own; writing override fun coat(colour: String, coats: Int = 3) is a compile error. The default lives on the base declaration alone.
  1. Assuming a default is evaluated once and cached. A default expression runs on every call that omits the argument. A default of mutableListOf() hands a fresh list to each such call, and a default that increments a counter advances it each time it runs -- never assume the value is computed a single time at definition.
  1. Expecting a default to be chosen by the runtime type of the receiver. For a virtual call through a base-typed variable, the default comes from the declared type while the body comes from the runtime type. The two can differ, and reasoning as though the override supplied the default leads to wrong predictions.
  1. Assuming Java callers see Kotlin defaults. The JVM has no notion of default arguments. Without the @JvmOverloads annotation, Java code sees only the full-arity method and cannot omit any parameter, which surprises teams calling Kotlin from Java.
  1. Giving a defaulted String option an else fallback. A when on a stringly-typed parameter that ends in else -> something swallows every misspelling into the fallback branch. The typo compiles, runs, and produces a wrong-but-plausible result with no diagnostic. A fixed set of options wants an enum, not a string.
  1. Relying on positional calls throughout a codebase. When every call site passes bare positional arguments, inserting a new parameter or reordering existing ones silently rebinds every call that still compiles. Named arguments at the call site survive such refactors; positional ones misbind quietly.
  1. Forgetting that parameter names are part of the public API. Once callers use named arguments, renaming a parameter breaks every named call site even though the types are unchanged. A rename that looks purely internal is a source-incompatible change for anyone who named that argument.

Best Practices

  • Prefer a single function with default arguments over a family of overloads; one signature with sensible defaults is easier to read and to keep consistent than four overloads that must agree.
  • Use named arguments at the call site for boolean flags and for any run of same-typed parameters, so a reader sees enabled = true, cached = false rather than a bare true, false whose meaning depends on memorised order.
  • Order parameters so the required ones come first, then the optionals from most- to least-commonly overridden, minimising how often callers must reach past a default by name.
  • Model a fixed set of choices as an enum or sealed type rather than a defaulted String with an else branch, so an invalid choice is a compile error instead of a silent fallback.
  • Add @JvmOverloads to any function with defaults that forms part of a Java-facing API, so Java callers get the overloads they expect.
  • Keep default expressions cheap and, where you can, free of side effects; when a default must have a side effect, document that it runs once per call that omits the argument.
  • State each default exactly once, on the base declaration, and never attempt to repeat or vary it in an override.
  • Treat parameter names as a committed part of the API the moment you expose defaults and named arguments, and rename them only as a deliberate, documented change.

Practice Exercises

  1. Write greet(name: String, greeting: String = "Hello", excited: Boolean = false): String that appends "!" when excited is true. Call it four ways -- all defaults, overriding only greeting, overriding only excited by name, and all three positionally -- and verify each output against a hand trace.
  1. Write a function whose third parameter defaults to a call that increments a shared counter. Call it five times, supplying the third argument on two of those calls and omitting it on three, then print the counter and confirm it equals exactly the number of calls that omitted the argument.
  1. Define an open class with a method that has a defaulted parameter, override that method in a subclass, and call it through a variable typed as the base class without supplying the optional argument. State which class provided the default value and which class provided the body that ran, and explain why.
  1. Take a function with a defaulted String mode parameter and a when that ends in else. Show that a misspelled mode is accepted and produces a fallback result with no error. Then refactor mode into an enum and show that the same misspelling now fails to compile.