KOTLIN: Functions in Kotlin

Functions in Kotlin are declared with the fun keyword and always return a value — Unit if nothing meaningful is returned. Kotlin supports default parameter values, named arguments, and expression bodies, making function definitions concise and flexible to call.

Functions are the primary mechanism for expressing behavior in Kotlin. Every action your code takes — calculating a value, updating state, responding to an event — is implemented in a function. Kotlin's approach to functions is designed to make them easy to define, flexible to call, and readable at both the declaration and the call site.


Declaring Functions

A function in Kotlin is declared using the fun keyword, followed by the function name, parameter list, optional return type, and body.

kotlin
fun greet(name: String): String {
    return "Hello, $name!"
}

The key parts:

  • fun — the keyword that declares a function
  • greet — the function name
  • (name: String) — the parameter list: each parameter is name: Type
  • : String — the return type annotation (after the parameter list)
  • { return "Hello, $name!" } — the function body

The Unit Return Type

Every function in Kotlin returns a value. If a function has no meaningful result to return, it returns Unit — Kotlin's equivalent of void in Java.

Unit is an actual type in Kotlin's type system (not a special keyword like void). A function that returns Unit explicitly still has a return value — it is just a value that carries no information.

The : Unit return type annotation is optional and typically omitted:

kotlin
// Explicit Unit return type
fun printMessage(message: String): Unit {
    println(message)
}

// Unit is implied when omitted — identical behavior
fun printMessage(message: String) {
    println(message)
}

Both declarations are equivalent. Convention is to omit : Unit.


Functions Inside Classes

Functions defined inside a class have access to the class's properties and can modify them:

kotlin
class Person(val name: String, var weightLbs: Double) {

    var weightKilos: Double
        get() = weightLbs / 2.2
        set(value) { weightLbs = value * 2.2 }

    // Unit return type is optional
    fun eatDessert(addedIceCream: Boolean = true): Unit {
        weightLbs += if (addedIceCream) 4.0 else 2.0
    }

    fun calcGoalWeightLbs(lbsToLose: Double = 10.0): Double {
        return weightLbs - lbsToLose
    }
}

Here, eatDessert() modifies weightLbs (a property of Person), and calcGoalWeightLbs() reads weightLbs to compute a result. Both functions operate in the context of the object they belong to.


Default Parameter Values

Kotlin functions can have default values for parameters. When a caller does not supply an argument for a parameter that has a default, the default value is used automatically.

This eliminates the need for multiple overloaded functions that differ only in which parameters are optional:

kotlin
fun eatDessert(addedIceCream: Boolean = true): Unit {
    weightLbs += if (addedIceCream) 4.0 else 2.0
}

Calling with and without the argument:

kotlin
val p = Person("Bob", 176.0)

p.eatDessert(false)  // Explicit: addedIceCream = false, adds 2.0 lbs
// weightLbs = 178.0

p.eatDessert()       // Default: addedIceCream = true, adds 4.0 lbs
// weightLbs = 182.0

Default parameters are evaluated at call time, not at definition time, which means they can reference other parameters or even compute a value.

kotlin
fun calcGoalWeightLbs(lbsToLose: Double = 10.0): Double {
    return weightLbs - lbsToLose
}

val goalWeight = p.calcGoalWeightLbs()      // Uses default: lbsToLose = 10.0
val aggressiveGoal = p.calcGoalWeightLbs(25.0)  // Overrides default


Positional and Named Arguments

Kotlin gives callers two ways to pass arguments to a function:

Positional Arguments

Arguments are matched to parameters by their position in the parameter list. The first argument goes to the first parameter, the second to the second, and so on. This is the same as Java and most other languages.

kotlin
val p1 = Person("Jim", 185.0)
// "Jim" -> name, 185.0 -> weightLbs

Named Arguments

Arguments are matched to parameters by name, regardless of order. This makes call sites more readable, especially for functions with multiple parameters of the same type, or functions where the meaning of a value is not obvious without context.

kotlin
val p2 = Person(weightLbs = 185.0, name = "Jim")
// Reordered — named arguments can appear in any order

Named arguments are particularly valuable when combined with default parameters. You can skip specific default parameters while overriding others:

kotlin
fun createUser(
    name: String,
    age: Int = 0,
    email: String = "",
    isAdmin: Boolean = false
)

// Using named arguments to skip some defaults
createUser(name = "Alice", isAdmin = true)
// age = 0 (default), email = "" (default)

Without named arguments, you would need to pass values for all preceding parameters even if you do not care about them, or define multiple overloads.


Expression Body Functions

For functions that consist of a single expression, Kotlin allows an expression body syntax that eliminates the return keyword and the braces:

kotlin
// Block body
fun add(a: Int, b: Int): Int {
    return a + b
}

// Expression body — equivalent, more concise
fun add(a: Int, b: Int): Int = a + b

// With type inference — the return type can also be omitted
fun add(a: Int, b: Int) = a + b

Expression bodies are particularly natural for simple calculations, transformations, and computed properties-as-functions.


Functions as First-Class Citizens

In Kotlin, functions are first-class citizens — they can be stored in variables, passed as arguments to other functions, and returned from functions.

kotlin
// Storing a function reference in a variable
val double: (Int) -> Int = { x -> x * 2 }

// Passing a function as an argument
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { x -> x * 2 }  // [2, 4, 6, 8, 10]

The { x -> x * 2 } syntax is a lambda expression — an anonymous function. Lambdas are heavily used in Kotlin for collection operations, event handlers, and coroutine builders.

When a lambda is the last argument to a function, Kotlin allows you to place it outside the parentheses (trailing lambda syntax):

kotlin
// Standard call
numbers.filter({ x -> x > 2 })

// Trailing lambda — cleaner when the lambda is the last argument
numbers.filter { x -> x > 2 }


Extension Functions

Kotlin allows you to add functions to existing classes without modifying their source code or subclassing them. These are called extension functions.

kotlin
// Add a function to String that repeats it N times
fun String.repeatTimes(n: Int): String = this.repeat(n)

val result = "ha".repeatTimes(3)  // "hahaha"

Extension functions appear to the caller as if they were members of the class being extended, but they do not actually modify the class. They are resolved statically at compile time.

Extension functions are used extensively in Kotlin's standard library and in Android's Jetpack libraries to add convenience methods to existing platform classes.


Summary

FeatureSyntax / Example
Function declarationfun name(param: Type): ReturnType { ... }
Unit return type: Unit (optional, usually omitted)
Default parametersfun foo(x: Int = 10)
Positional argumentsfoo(42)
Named argumentsfoo(x = 42)
Expression bodyfun add(a: Int, b: Int) = a + b
Lambda expression{ x -> x * 2 }
Trailing lambdalist.filter { it > 0 }
Extension functionfun String.shout() = this.uppercase() + "!"

Functions in Kotlin are expressive, flexible, and designed to reduce the ceremony around common patterns. Default parameters eliminate overload proliferation, named arguments make call sites self-documenting, and first-class function support enables the powerful functional patterns used throughout the Kotlin standard library and Android Jetpack.

Write functions that say exactly what they do, with exactly the parameters they need.