Functions, Default & Named Arguments
Declaring functions
A function is a reusable block of code. Kotlin functions are concise and support several conveniences that make calling code clearer.
fun add(a: Int, b: Int): Int {
return a + b
}
// single-expression form (the return type is inferred)
fun multiply(a: Int, b: Int) = a * b
Default arguments
Give parameters default values so callers can skip them — this removes the need for many overloaded versions of the same function.
fun greet(name: String, greeting: String = "Hi") = "$greeting, $name!"
greet("Anand") // "Hi, Anand!"
greet("Priya", "Hello") // "Hello, Priya!"
Named arguments
When a function has several parameters, naming them at the call site makes the code self-documenting and lets you pass them in any order.
fun createUser(name: String, age: Int = 18, active: Boolean = true) { }
createUser(name = "Anand", active = false) // skip age, name 'active'
createUser(age = 30, name = "Priya") // any order when named
Returning nothing, or multiple values
fun log(msg: String): Unit { // Unit means "no useful return" (can be omitted)
println(msg)
}
// return two values with a Pair (or a data class)
fun minMax(nums: List<Int>): Pair<Int, Int> = Pair(nums.min(), nums.max())
val (low, high) = minMax(listOf(3, 9, 1)) // destructuring
vararg: any number of arguments
fun sumAll(vararg numbers: Int): Int = numbers.sum()
sumAll(1, 2, 3, 4) // 10
Local functions
You can define a function inside another to organise logic that’s only used there:
fun process(data: List<Int>) {
fun isValid(x: Int) = x > 0
val clean = data.filter { isValid(it) }
}
Common mistakes
- Writing several overloaded functions when a default argument would do.
- Long parameter lists with no names at the call site — use named arguments for clarity.
- Returning a generic
Pairwhen a smalldata classwould read better.
Summary: Use single-expression functions for short logic, default + named arguments instead of overloads, and destructuring to unpack returned pairs.