Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 134 ยท Functions

Default and Named Arguments

Learn Kotlin default parameter values and named arguments - how to skip arguments, mix positional and named calls, avoid overloads and use @JvmOverloads for Java.

Think about a function that sends an email. It needs a recipient and a body for sure, but also a subject, a priority, maybe a reply-to address. Most callers only care about the first two. In many languages you would write five versions of the function with different parameter lists, or force everyone to pass null for what they do not need. Kotlin solves this with two small features that work together: default argument values and named arguments.

With them, one function declaration can serve simple and detailed calls, and call sites read almost like sentences: connect(host = "localhost", timeoutSeconds = 5). This lesson shows how both features work, the rules for mixing them, why they usually replace overloads, and what to do when Java code needs to call your function.

Default values

Give a parameter a default by writing = value after its type. A caller may then leave that argument out, and Kotlin fills in the default.

Kotlin Defaults fill in the missing arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three calls print Hello, Ada!, Welcome, Ada! and Good evening, Ada.. When you pass arguments positionally, they fill the parameters from left to right, and every parameter you did not reach uses its default. A parameter without a default is required: calling greet() would be an error, because Kotlin has no value for name.

A default can be any expression, not only a literal. It is computed at call time, each time the argument is missing, and it may use parameters that appear earlier in the list:

Kotlin Defaults can use earlier parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

box(4) becomes a square, because height defaults to width; the label is then built from both, giving 4x4 (area 16). Defaults to the right of a parameter may depend on it, but not the other way around.

Named arguments

Positional arguments only work when you remember the order. With a call like createUser("ada", true, false, 30), nobody can tell what true and false mean. Naming the arguments fixes that:

Kotlin Named arguments make calls readable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Named arguments give you three things at once:

  1. Readability: isAdmin = true explains itself. Prefer names for any Boolean or any number whose meaning is not obvious.
  2. Skipping: you can leave out defaults in the middle. The call createUser("grace", isAdmin = true) keeps the defaults for isActive and maxSessions without you having to repeat them.
  3. Any order: maxSessions = 10, isAdmin = true is fine, because each value is matched by name.

The trailing comma after the last parameter (maxSessions: Int = 3,) is allowed in Kotlin and makes diffs cleaner when parameters are added.

Mistakes the compiler catches

Two mistakes come up often. The first is skipping a parameter that has no default; the second is a typo in a name.

Kotlin A required parameter is missing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is main.kt:4:13: error: no value passed for parameter 'name'. Defaults make arguments optional, but only the parameters that have them.

Kotlin A misspelled name (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here the compiler says main.kt:4:26: error: no parameter with name 'greting' found. Named arguments are checked at compile time, which is another reason to prefer them over comments like /* isAdmin */ true. The fix is spelling the name greeting, which prints Hi, Ada!.

Renaming a parameter is therefore a breaking change for callers that use named arguments. For a public API, choose parameter names carefully.

Mixing positional and named arguments

You may mix both styles in one call. The rule is simple: positional arguments come first, in order, and named ones follow. Since Kotlin 1.4 you may also place a named argument before positional ones, but only if every argument stays in its own position, so the order still matches the declaration.

Kotlin Named arguments in the wrong position (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler reports two errors: main.kt:4:13: error: no value passed for parameter 'w'. and main.kt:4:24: error: mixing named and positional arguments is not allowed unless the order of the arguments matches the order of the parameters. The named h = 2 jumped ahead of w, so the positional 3 no longer has an obvious home. Either name everything, or keep positional arguments first:

Kotlin Valid ways to mix them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The results are 6, 15, 6 and 24. In the third call w = 3 is named but stays in the first slot, so the positional 2 that follows still lands on h. That is the "order still matches" exception. In practice, the cleanest style is: required arguments positionally, optional ones by name.

Defaults instead of overloads

Without defaults, you would write a family of overloads:

Kotlin
fun connect(host: String) = connect(host, 80)
fun connect(host: String, port: Int) = connect(host, port, 30)
fun connect(host: String, port: Int, timeout: Int) { /* real work */ }

With defaults, one function replaces all three: fun connect(host: String, port: Int = 80, timeout: Int = 30). That is shorter, there is only one place with logic, and named arguments let callers set timeout alone. Prefer defaults whenever the "missing" arguments have a sensible default value.

Use real overloads when the functions take genuinely different kinds of input (for example parse(text: String) and parse(bytes: ByteArray)), or when the default would depend on something complicated.

Overriding and defaults

An overriding function must not declare its own defaults. It inherits the defaults from the function it overrides. This keeps behavior consistent, whatever the static type of the variable:

Kotlin An override inherits the default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

LoudPrinter.print writes no = 1, yet p.print("hello") works and prints one copy, because the default belongs to the base declaration. Writing a default on an override is a compile error.

Defaults and nullable parameters

Do not use null as a stand-in for "not provided" when a real default exists. Compare:

Kotlin
fun fetch(url: String, timeoutSeconds: Int? = null)   // what does null mean?
fun fetch(url: String, timeoutSeconds: Int = 30)      // clear

Use a nullable default only when null is a meaningful value in its own right, such as "no timeout at all" or "no filter". Then document it.

Defaults and Java: @JvmOverloads

Java has no default arguments. A Kotlin function greet(name: String, greeting: String = "Hello") compiles to a single method with two parameters, and Java code must pass both. If your Kotlin code is meant to be called from Java, add @JvmOverloads and Kotlin generates the shorter overloads for you.

This is a read-only example, since the runner compiles only Kotlin:

Kotlin
@JvmOverloads
fun connect(host: String, port: Int = 80, secure: Boolean = false) { /* ... */ }

// Java sees three methods:
//   connect(String host)
//   connect(String host, int port)
//   connect(String host, int port, boolean secure)

Note that overloads are generated by removing parameters from the right, one at a time, so you cannot get "host and secure but not port" from Java. Named arguments are a Kotlin-only feature, and Java callers can never use them. If you write only Kotlin, you never need this annotation.

Evaluation order

Default values are evaluated when the call happens, in the order of the parameters. When you pass arguments by name in a different order, Kotlin still evaluates the argument expressions in the order you wrote them at the call site, which matters when they have side effects:

Kotlin Arguments run in the order written

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output starts with evaluating height, then evaluating width, then volume = 12. The call-site order wins, even though width is declared first.

Design notes and pitfalls

  • Group related options. If a function has more than four or five optional parameters, consider a small data class of options or a builder. Long lists of defaults are hard to evolve.
  • Do not reorder parameters carelessly. Positional callers silently break (or worse, still compile) when two parameters of the same type swap places.
  • Use named arguments for same-typed parameters. copy(from = a, to = b) cannot be mixed up; copy(a, b) can.
  • Defaults that allocate (a new list, say) run on every call that omits the argument. That is usually what you want, because each call gets its own list, but it surprises people used to Python's shared default objects.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given fun f(a: Int, b: Int = 2, c: Int = 3), which call is valid?

    a has no default, so it must be passed. f(1, c = 9) passes a positionally and skips b. The call f(c = 9, 1) is rejected because the named argument is out of position.
  2. 2. What does the compiler say for greet("Ada", greting = "Hi") when the parameter is spelled greeting?

    Named arguments are matched against the declared parameter names at compile time, so a typo is an error.
  3. 3. An overriding function declares override fun print(text: String, copies: Int). Where do its default values come from?

    Overrides inherit the defaults of the overridden function and may not declare their own.
  4. 4. Why use @JvmOverloads?

    Java does not understand default arguments. @JvmOverloads generates extra overloads, dropping optional parameters from the right.
  5. 5. In which order are argument expressions evaluated in rectangle(height = trace("h"), width = trace("w"))?

    Kotlin evaluates arguments in the order they are written at the call site, regardless of the parameter order in the declaration.

Summary

  • Write param: Type = value to give a parameter a default; callers may then omit it.
  • Defaults are expressions evaluated at call time and may use earlier parameters.
  • Named arguments (name = value) make calls readable, let you skip defaults in the middle and allow any order.
  • Positional arguments come first; a named argument may precede positional ones only if every argument keeps its own position.
  • Defaults usually replace families of overloads; overrides inherit defaults and cannot redeclare them.
  • Use @JvmOverloads only when Java must call the function; prefer a real default over null as a "not given" marker.

Next: Varargs and the Spread Operator