Named Arguments
In this page:
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
fun createRectangle(width: Int, height: Int): String {
return "Rectangle ${width}x$height"
}
fun main() {
println(createRectangle(width = 10, height = 5))
}
Login to try C/C++/Java/PHP code in the editor
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
fun createRectangle(width: Int, height: Int): String {
return "Rectangle ${width}x$height"
}
fun main() {
println(createRectangle(height = 5, width = 10))
}
Login to try C/C++/Java/PHP code in the editor
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
fun createUser(name: String, age: Int = 18, active: Boolean = true): String {
return "$name (age $age, active=$active)"
}
fun main() {
println(createUser("Carol", active = false))
}
Login to try C/C++/Java/PHP code in the editor
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
fun configure(darkMode: Boolean, notifications: Boolean, autoSave: Boolean) {
println("dark=$darkMode, notify=$notifications, autoSave=$autoSave")
}
fun main() {
configure(darkMode = true, notifications = false, autoSave = true)
}
Login to try C/C++/Java/PHP code in the editor
- Mixing named and positional arguments incorrectly; once you use a named argument, arguments after it should generally also be named.
- Assuming named arguments change performance or behavior; they only affect readability and call-site flexibility.
- Not using named arguments for functions with several
Booleanparameters, making call sites hard to read (e.g.f(true, false, true)).
- 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: