Part 05 / Topic 4 of 8
Default and named arguments
A default argument gives a parameter a value to use when the caller doesn't supply one. A named argument lets a caller supply a value by the parameter's name instead of its position -- useful the moment a function has more than a couple of parameters, or when you want to skip over an earlier default without repeating it.
fun priceAfterDiscount(amount: Double, percent: Double = 0.0, membership: String = "regular"): String {
val discounted = amount - amount * percent / 100
return "₹%.2f after %.1f%% discount (%s member)".format(discounted, percent, membership)
}
fun main() {
println(priceAfterDiscount(1000.0)) // all defaults
println(priceAfterDiscount(1000.0, 10.0)) // positional
println(priceAfterDiscount(1000.0, percent = 20.0)) // named, skip membership's default
println(priceAfterDiscount(amount = 2000.0, membership = "gold", percent = 15.0)) // all named, reordered
}
₹1000.00 after 0.0% discount (regular member)
₹900.00 after 10.0% discount (regular member)
₹800.00 after 20.0% discount (regular member)
₹1700.00 after 15.0% discount (gold member)
Named arguments can arrive in any order, which is why the last call reorders membership
before percent with no issue -- the names, not the positions, decide where each value lands. A
default argument's value may itself refer to an earlier parameter:
fun billWithGst(amount: Double, gst: Double = amount * 0.18): String {
return "Amount ₹%.2f + GST ₹%.2f = ₹%.2f".format(amount, gst, amount + gst)
}
$ kotlinc 04_default_and_named_arguments.kt -include-runtime -d d04.jar && java -jar d04.jar
...
Amount ₹500.00 + GST ₹90.00 = ₹590.00
Amount ₹500.00 + GST ₹0.00 = ₹500.00
The second call, billWithGst(500.0, gst = 0.0), proves gst's default is only a fallback --
naming it overrides the computed default outright, same as naming any other parameter.
Full program: examples/04_default_and_named_arguments.kt.
Done here? The practice set for Part 5 — including the solutions — is on the part page.