Default and Named Arguments

Default Arguments

Example

Give a parameter a default value with =. Callers can then leave it out. This removes the need for many overloaded versions, as in Java.

fun formatPrice(amount: Int, currency: String = "₹", showDecimals: Boolean = false): String {
    return if (showDecimals) "$currency$amount.00" else "$currency$amount"
}

fun main() {
    println(formatPrice(499))
    println(formatPrice(499, "$"))
    println(formatPrice(499, "₹", true))
}

Output

₹499
$499
₹499.00

Named Arguments

Example

Name the arguments at the call site to make the code readable and to skip some defaults. Named arguments can be in any order.

fun sendNotification(
    title: String,
    body: String,
    silent: Boolean = false,
    priority: Int = 1,
) {
    println("[$priority] $title - $body (silent=$silent)")
}

fun main() {
    sendNotification("Order update", "Your food is ready")
    sendNotification("Offer", "50% off today", priority = 2)
    sendNotification(body = "Backup completed", title = "Drive", silent = true)
}

Output

[1] Order update - Your food is ready (silent=false)
[2] Offer - 50% off today (silent=false)
[1] Drive - Backup completed (silent=true)

Tip: Named arguments are used heavily in Jetpack Compose: Text(text = "Hi", fontSize = 18.sp, color = Color.Gray).