← Back to Kotlin Course | Chapter 4: Functions | Lesson 3 of 7

Named Arguments

Named arguments let you say exactly which parameter you're filling in by name, instead of relying only on the order you list them.

Basic Named Arguments

Instead of relying on position, you can specify parameterName = value explicitly when calling a function, which makes the call self-documenting.

Example: Basic Named Arguments

markup
fun createRectangle(width: Int, height: Int): String {
    return "Rectangle ${width}x$height"
}

fun main() {
    println(createRectangle(width = 10, height = 5))
}

Reordering with Named Arguments

Because named arguments are matched by name rather than position, they can be passed in a different order than they were declared.

Example: Reordering with Named Arguments

markup
fun createRectangle(width: Int, height: Int): String {
    return "Rectangle ${width}x$height"
}

fun main() {
    println(createRectangle(height = 5, width = 10))
}

Skipping Defaults with Named Arguments

Named arguments let you override just one later default parameter without having to also repeat the earlier defaults you're happy to keep.

Example: Skipping Defaults with Named Arguments

markup
fun createUser(name: String, age: Int = 18, active: Boolean = true): String {
    return "$name (age $age, active=$active)"
}

fun main() {
    println(createUser("Carol", active = false))
}

Improving Readability

For functions with several parameters of the same type, such as multiple booleans, named arguments make the call site far easier to understand at a glance.

Example: Improving Readability

markup
fun configure(darkMode: Boolean, notifications: Boolean, autoSave: Boolean) {
    println("dark=$darkMode, notify=$notifications, autoSave=$autoSave")
}

fun main() {
    configure(darkMode = true, notifications = false, autoSave = true)
}
Common Mistakes
  1. Mixing named and positional arguments incorrectly; once you use a named argument, arguments after it should generally also be named.
  2. Assuming named arguments change performance or behavior; they only affect readability and call-site flexibility.
  3. Not using named arguments for functions with several Boolean parameters, making call sites hard to read (e.g. f(true, false, true)).
Chapter Summary
  • Named arguments are passed as parameterName = value, independent of declaration order.
  • They greatly improve readability for functions with many parameters or several parameters of the same type.
  • Named arguments can be combined with default parameters to skip earlier defaults while setting a later one.
  • Once a named argument is used, any following arguments in that call should also be named for clarity (and sometimes are required to be).
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.