typestar

Defaults and named arguments in Kotlin

Signatures carry the defaults, so call sites stay short.

// Default values live in the signature; = makes an expression body.
fun paceMinPerKm(minutes: Int, km: Double = 10.0) = minutes / km

fun campNote(site: String, tents: Int = 1, fires: Boolean = false): String {
    val fireNote = if (fires) "fire ring in use" else "no fires"
    return "$site: $tents tents, $fireNote"
}

fun main() {
    println(paceMinPerKm(85))
    // Named arguments skip past the defaults you keep.
    println(campNote("Boulder Flats", fires = true))
}

How it works

  1. km: Double = 10.0 is a default; = after the signature is an expression body.
  2. campNote mixes required and defaulted parameters in one signature.
  3. campNote("Boulder Flats", fires = true) names an argument to skip the rest.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
457
Tokens
95
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 3 in Functions, step 7 of 27 in Language basics.

← Previous Next →

Defaults and named arguments in other languages