Kotlin Default Arguments
A default argument is a value a parameter uses when a call leaves that argument out. A call can still pass a real value and replace the default.
A greeting with a default name
greet carries the default name friend in its definition. The first call leaves the name out and the second call passes a name.
fun greet(name: String = "friend") {
println("Hello, $name")
}
fun main() {
greet()
greet("Ana")
}A default tax rate
total adds a tax of 5 when the call gives no tax. The second call passes 20 and replaces the default.
fun total(price: Int, tax: Int = 5): Int {
return price + tax
}
fun main() {
println(total(100))
println(total(100, 20))
}Replacing only the default by name
The price stays positional here and the tax is named. Only the default changes in this call.
fun total(price: Int, tax: Int = 5): Int {
return price + tax
}
fun main() {
println(total(200, tax = 10))
}Example
fun makeLabel(name: String, label: String = "guest"): String {
return "$name is a $label"
}
fun main() {
println(makeLabel("Ana"))
println(makeLabel("Bo", "member"))
println(makeLabel("Cy", label = "host"))
}Key points
- Write a default with an = sign after the parameter name in the definition.
- Use a default to make an argument optional at a call.
- A call that passes no value for a parameter uses its default.
- A call can replace a default by passing a value for that parameter.
In this example, makeLabel takes a name and a label with the default guest. The first call passes only a name, so the default fills the label. The second call passes a label in the normal position. The third call names the label and replaces the default that way.
Note
A parameter with no default must still get a value at every call.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A parameter has the default value 10. A call passes no value for it. Which value does the function use?