Default Parameters
In this page:
Declaring a Default Value
Assigning a value directly in the parameter list, like greeting: String = "Hello", makes that parameter optional -- callers who don't pass it get the default.
Example: Declaring a Default Value
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
fun main() {
println(greet("Kotlin"))
}
Login to try C/C++/Java/PHP code in the editor
Overriding a Default
A caller can still pass a value for a parameter that has a default, which simply overrides that default for this particular call.
Example: Overriding a Default
fun greet(name: String, greeting: String = "Hello"): String {
return "$greeting, $name!"
}
fun main() {
println(greet("Kotlin", "Welcome"))
}
Login to try C/C++/Java/PHP code in the editor
Multiple Default Parameters
A function can have several parameters with defaults, letting callers omit any combination of the trailing ones freely.
Example: Multiple Default Parameters
fun createUser(name: String, age: Int = 18, active: Boolean = true): String {
return "$name (age $age, active=$active)"
}
fun main() {
println(createUser("Alice"))
println(createUser("Bob", 25))
}
Login to try C/C++/Java/PHP code in the editor
Defaults Avoid Overloading
Instead of writing several overloaded functions for each combination of arguments, a single function with defaults covers all the common cases concisely.
Example: Defaults Avoid Overloading
fun power(base: Int, exponent: Int = 2): Int {
var result = 1
repeat(exponent) { result *= base }
return result
}
fun main() {
println("Square: ${power(5)}")
println("Cube: ${power(5, 3)}")
}
Login to try C/C++/Java/PHP code in the editor
- Assuming Kotlin needs overloaded functions like Java for optional parameters, instead of using a single function with defaults.
- Putting a non-default parameter after a parameter with a default value without using named arguments, which can force awkward call sites.
- Forgetting that default values are re-evaluated for every call, not computed once and shared across calls.
- A default value is written as
parameter: Type = valuein the function declaration. - Callers may omit any parameter that has a default, and the default value is used instead.
- Default parameters remove the need for multiple overloaded functions in many cases.
- Combining default parameters with named arguments makes it easy to skip some defaults while overriding others.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: