Kotlin Anonymous Functions

A regular function carries a name, and you call it by that name. An anonymous function skips the name. You write it right where you need it, or store it in a variable. Think of a temporary worker who joins a project for one task and wears no name badge.

Three Ways to Write a Function

 Named function      fun double(x: Int): Int = x * 2
 Lambda              { x: Int -> x * 2 }
 Anonymous function  fun(x: Int): Int = x * 2

All three do the same math. Each one offers a different style. The anonymous function looks like a normal function with the name removed.

Basic Syntax

fun main() {
    val double = fun(x: Int): Int {
        return x * 2
    }
    println(double(5))   // 10
}

The keyword fun starts the function, and the parentheses hold the parameters. The return type follows a colon. The variable double holds the whole function, and the call double(5) runs it.

Short Form

A single expression can replace the braces:

val square = fun(x: Int): Int = x * x
println(square(4))   // 16

Passing to Another Function

Functions such as filter accept a function as input. An anonymous function works as that input.

fun main() {
    val numbers = listOf(1, 2, 3, 4, 5, 6)
    val evens = numbers.filter(fun(n: Int): Boolean {
        return n % 2 == 0
    })
    println(evens)   // [2, 4, 6]
}

Why Choose an Anonymous Function

Lambdas cover most needs, and they look shorter. Anonymous functions shine in two situations.

  • The code needs an explicit return type that stays visible to readers.
  • The body needs a return that exits only the function itself.

The Return Difference

The word return behaves differently in each style. Inside an anonymous function, return leaves that function only. Inside a lambda passed to an inline function such as forEach, return leaves the whole surrounding function.

fun withAnonymous() {
    listOf(5, 20, 7).forEach(fun(n: Int) {
        if (n > 10) return
        println(n)
    })
    println("done")
}

fun withLambda() {
    listOf(5, 20, 7).forEach {
        if (it > 10) return
        println(it)
    }
    println("done")
}

The first function prints 5, then 7, then done. The anonymous function skips 20 and the loop continues. The second function prints 5 and stops completely. The word done never appears, because return left withLambda.

 Anonymous:  5 --> 20 (return, skip) --> 7 --> "done"
 Lambda:     5 --> 20 (return, EXIT everything)

Parameter Types and Inference

A lambda often infers its parameter type from context. An anonymous function must state parameter types in most cases. The extra words add clarity for the reader and the compiler.

Anonymous Function with Receiver

A receiver gives the function a hidden this object. The syntax places the receiver type before the dot.

val shout = fun String.(): String = this.uppercase() + "!"
println("hello".shout())   // HELLO!

This form builds small helper tools that look like built-in features of the String type.

Storing and Reusing

A variable holds the function, so one function can serve many calls. A list can hold several functions too:

val add = fun(a: Int, b: Int): Int = a + b
val multiply = fun(a: Int, b: Int): Int = a * b
val tools = listOf(add, multiply)

for (tool in tools) {
    println(tool(3, 4))
}

The loop prints 7 and then 12.

Quick Comparison

FeatureLambdaAnonymous Function
SyntaxCurly bracesfun keyword
Return typeInferredWritten in the code
return keywordLeaves the outer functionLeaves itself
Typical useShort actionsClear control flow