thecodex.expert · The Codex Family of Knowledge
Kotlin

Functions

Java needed 3 or 4 overloaded methods to offer optional parameters — Kotlin does the same job with ONE function and default parameter values.

Kotlin 2.1 Default params replace most overloads Last verified:
Canonical Definition

fun name(params): ReturnType declares a function; parameters can specify a default value, letting callers omit them entirely, and named arguments let a call specify parameters by name rather than strict position — together, these two features cover most of the use cases that required overloaded methods in Java. A single-expression function (fun square(x: Int) = x * x, with no braces or explicit return) is idiomatic for simple one-line bodies, letting the return type often be inferred too.

Default parameters: one function instead of several overloads

Java would typically need 2-3 overloaded methods to offer this same flexibility; Kotlin needs exactly one function, with callers choosing how many arguments to actually supply.

Kotlindefault_params.kt
fun greet(name: String, greeting: String = "Hello") {
    println("$greeting, $name!")
}

greet("Alice")                  // "Hello, Alice!" — greeting uses its default
greet("Bob", "Welcome")          // "Welcome, Bob!" — greeting explicitly overridden

Named arguments: clarity at the call site

Named arguments can be supplied in ANY order, and are especially valuable when a function has several parameters of the same type, where positional-only calls become genuinely easy to misread or get wrong.

Kotlinnamed_arguments.kt
fun createUser(name: String, age: Int, isAdmin: Boolean = false) { /* ... */ }

createUser(name = "Alice", age = 30, isAdmin = true)
createUser(age = 25, name = "Bob")   // order doesn't matter when named

Single-expression functions

No braces, no explicit return keyword, and the return type is often inferred from the expression — idiomatic for genuinely simple, one-line function bodies.

Kotlinsingle_expression.kt
fun square(x: Int) = x * x               // return type inferred as Int
fun isEven(n: Int): Boolean = n % 2 == 0   // explicit return type, still one line

println(square(5))     // 25
println(isEven(4))       // true

Sources

1
JetBrains. Kotlin Documentation, "Functions," kotlinlang.org/docs/functions.html.