Named arguments and default values
Named arguments and default values
Kotlin function calls can read like descriptions of a task. Argument labels are names used at the call site, while parameter names are used inside the body. A default parameter lets a caller omit one argument when a sensible standard value exists.
What you’ll learn
- Use named arguments and defaults.
- Keep an update explicit through a returned value.
Named arguments and default values in the example
Original score
Keep the input score unchanged.
70Choose arguments
Use the default five or the named amount eight.
addBonus(score, amount)Return results
Each call produces a new numeric value.
75 and 78; original 70
Understand named arguments and default values
Named arguments identify a parameter at the call site, and defaults supply values for omitted arguments. Kotlin does not use Swift-style inout parameters for ordinary numeric variables; returning a corrected value keeps the state update visible in the caller.
Follow named arguments and default values
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun addBonus(score: Int, amount: Int = 5): Int = score + amount
fun main() {
val score = 70
println(addBonus(score = score))
println(addBonus(amount = 8, score = score))
println(score)
}Expected output
75
78
70Follow the execution
The first call uses default five and returns 75. The named second call uses eight and returns 78. Neither changes the original score, which remains 70; the caller can assign a returned result to a var when updating state is intended.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Named arguments and default values
Your task: How do you request an eight-point bonus without mutating the input?
Kotlin/JVM · complete program
fun addBonus(score: Int, amount: Int = 5): Int = score + amount
fun main() {
val score = 70
println(addBonus(score = score))
println(addBonus(amount = 8, score = score))
println(score)
}Worked answer
Call addBonus(score = score, amount = 8) and use its returned value. Named arguments clarify which quantity is changing.
Named arguments and default values: the important boundary
Defaults should express a meaningful common policy rather than hide required information. Named arguments are not generally available when calling Java methods, whose parameter-name contract differs. Use vararg only when a variable argument count fits the function.
Check your understanding
Named arguments and default values: what to keep in mind
Call addBonus(score = score, amount = 8) and use its returned value. Named arguments clarify which quantity is changing. Defaults should express a meaningful common policy rather than hide required information.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.