Menu
Coddy logo textTech

Default Values

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 59 of 93.

Sometimes you want a function parameter to have a fallback value when the caller doesn't provide one. Kotlin lets you assign default values directly in the parameter definition.

fun greet(name: String = "Guest") {
    println("Hello, $name!")
}

fun main() {
    greet("Alice")
    greet()
}
// Output:
// Hello, Alice!
// Hello, Guest!

When calling greet() without an argument, Kotlin uses the default value "Guest". This makes functions more flexible - callers can customize behavior when needed or rely on sensible defaults.

You can mix parameters with and without defaults. Parameters with defaults typically come last:

fun createUser(name: String, role: String = "member"): String {
    return "$name ($role)"
}

fun main() {
    println(createUser("Alice", "admin"))
    println(createUser("Bob"))
}
// Output:
// Alice (admin)
// Bob (member)

Named arguments become especially useful with default values. They let you skip parameters while providing others:

fun format(text: String, uppercase: Boolean = false, prefix: String = "") {
    val result = if (uppercase) text.uppercase() else text
    println("$prefix$result")
}

fun main() {
    format("hello", prefix = "-> ")
}
// Output: -> hello
challenge icon

Challenge

Medium

Implement buildGreeting(name: String, greeting: String = "Hello"): String. Return a greeting in the form greeting, name!. The supplied test driver calls your function twice: once with just the name, and once with a name and an explicit greeting. Do not write main or print inside the function. The missing greeting must use the default "Hello".

Try it yourself

fun buildGreeting(name: String, greeting: String): String {
    // Add the default value to the parameter and return the greeting.
    TODO("Build the greeting")
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground