A function is declared with fun, its parameters are name-then-type, and the return type comes after the parameter list. A function that returns nothing returns Unit, which you almost never write down.
Two features together remove most of the reason to overload a method. Default arguments let a parameter have a value used when the caller omits it, so one function replaces the family of four that Java would need. Named arguments let the caller say which parameter they mean, which both allows skipping defaults in the middle and makes call sites readable - a bare true at a call site tells a reader nothing, while includeArchived = true tells them everything.
When a function body is a single expression, the braces and the return keyword can go, replaced by an equals sign. The return type can usually be inferred too. This is not merely shorter; it signals to the reader that the function computes a value and does nothing else.
One rule that catches newcomers: once you use a named argument, you may still pass later arguments positionally in Kotlin, but mixing the two styles confusingly is the main source of argument-order bugs. Pick one style per call.
// Default arguments remove the need for four overloads
fun greet(name: String, greeting: String = "Hello", excited: Boolean = false): String {
val mark = if (excited) "!" else "."
return "$greeting, $name$mark"
}
// A single-expression function: no braces, no return
fun square(n: Int) = n * n
fun main() {
println(greet("Ada")) // Hello, Ada.
println(greet("Ada", "Welcome")) // Welcome, Ada.
println(greet("Ada", excited = true)) // skips the middle default
println(greet(name = "Ada", greeting = "Hi")) // named, self-documenting
println(square(7)) // 49
}
Discussion
No questions on this topic yet. Sign in to ask the first one.