Function Declarations

Function Declarations, Default and Named Arguments

A function starts with fun, types each parameter after a colon and declares its return type after the parameter list. A single-expression body can be written = expression, with the return type inferred. Functions can sit at the top level of a file, outside any class.

Default and named arguments in BookNest's price formattingKotlin
fun formatPrice(amount: Double, currency: String = "USD", decimals: Int = 2): String {
  val symbol = if (currency == "USD") "$" else "$currency "
  return symbol + "%.${decimals}f".format(amount)
}
fun main() {
  println(formatPrice(14.99))
  println(formatPrice(decimals = 0, amount = 24.0))
  println(formatPrice(18.75, currency = "MYR"))
}
Output
$14.99
$24
MYR 18.75

To skip currency in JavaScript, you write formatPrice(24, undefined, 0) or switch to an options object. Kotlin lets you name the arguments you want, in any order. That is how Compose 234 's Text offers a dozen optional parameters with no builder: you pass fontSize and maxLines by name. A vararg parameter works like a rest parameter, collecting arguments into an array, and * spreads an existing array into one.