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

Default Parameters

Default parameters let a function already know what value to use if you don't bother giving it one yourself.

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

markup
fun greet(name: String, greeting: String = "Hello"): String {
    return "$greeting, $name!"
}

fun main() {
    println(greet("Kotlin"))
}

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

markup
fun greet(name: String, greeting: String = "Hello"): String {
    return "$greeting, $name!"
}

fun main() {
    println(greet("Kotlin", "Welcome"))
}

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

markup
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))
}

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

markup
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)}")
}
Common Mistakes
  1. Assuming Kotlin needs overloaded functions like Java for optional parameters, instead of using a single function with defaults.
  2. Putting a non-default parameter after a parameter with a default value without using named arguments, which can force awkward call sites.
  3. Forgetting that default values are re-evaluated for every call, not computed once and shared across calls.
Chapter Summary
  • A default value is written as parameter: Type = value in 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:

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.