Kotlin's function features remove most overloads and builder boilerplate common in Java.
Functions are declared with fun, typed parameters and a return type after a colon:
fun add(a: Int, b: Int): Int { return a + b }A single-expression function drops the braces and usually the return type: fun add(a: Int, b: Int) = a + b. Functions with no useful result return Unit (Kotlin's void), which you don't need to write.
Parameter features:
- Default values:
fun greet(name: String, greeting: String = "Hello"). This replaces most Java overloads. - Named arguments:
greet(name = "Ada", greeting = "Hi")makes calls self-documenting, and lets you skip defaults or pass arguments in any order. vararg:fun sum(vararg xs: Int); pass an array with the spread operatorsum(*arr).- Parameters are read-only (
val); you can't reassign them.
Functions can live at top level (no class needed), inside classes (methods), or inside other functions (local functions) to hide helpers. Kotlin has no static keyword; top-level functions fill that role.
Infix functions (infix fun Int.times(s: String)) allow 2 times "ab", and the standard library's to builds pairs this way: "a" to 1.
To return several values, return a Pair, Triple or (better) a small data class, and destructure it: val (min, max) = range(xs).
Example
fun add(a: Int, b: Int) = a + b
fun greet(name: String, greeting: String = "Hello", punct: String = "!") =
"$greeting, $name$punct"
fun sum(vararg xs: Int): Int = xs.sum()
fun minMax(xs: List<Int>): Pair<Int, Int> = xs.min() to xs.max()
fun main() {
println(add(2, 3)) // 5
println(greet("Ada")) // Hello, Ada!
println(greet("Ada", punct = "?")) // Hello, Ada?
println(greet(greeting = "Hi", name = "Bo"))// Hi, Bo!
println(sum(1, 2, 3)) // 6
val arr = intArrayOf(4, 5)
println(sum(*arr)) // 9
val (lo, hi) = minMax(listOf(4, 9, 1))
println("$lo..$hi") // 1..9
fun square(x: Int) = x * x // local function
println(square(7)) // 49
}Remember
- fun name(p: Type): Return; single-expression bodies use =
- Default and named arguments replace most overloads
- Top-level functions replace static utility methods
- Return Pair or a data class and destructure it