Anonymous Functions in Kotlin
Introduction
Anonymous Functions is a fundamental concept every Kotlin developer should understand. Lambda expressions are anonymous functions you can pass as values — the foundation of functional-style APIs in Kotlin.
Anonymous functions look like regular functions without a name. In this tutorial you will learn the syntax, walk through a complete example program, study the sample output, and review best practices so you can apply the concept confidently in your own projects.
Definition
- Anonymous functions look like regular functions without a name.
- They support multiple return points using return keyword.
- Useful when return is needed inside nested logic.
Syntax
fun(x: Int): Int { return x + 1 }Anonymous Functions in Kotlin Example Program in Kotlin
fun main(args: Array<String>) {
val increment = fun(x: Int): Int {
if (x < 0) return 0
return x + 1
}
println(increment(4))
}Sample Output
5When to use
Use lambdas for short callbacks passed to collection operations, event handlers, or higher-order functions.
How it works
-
The program starts with a
mainfunction — the entry point that runs when you execute the file. -
val increment = fun(x: Int): Int {assigns or updates a value used later in the program. -
The
println(increment(4))statement writes a line to the console — this produces part of the sample output below. -
Anonymous functions look like regular functions without a name.
-
Run the program in IntelliJ IDEA, Android Studio, or with the Kotlin command-line compiler (
kotlinc/kotlin). Compare your console output with the sample output shown below.
Best Practices
Common Mistakes
Key Points
- Anonymous functions look like regular functions without a name.
- They support multiple return points using return keyword.
- Useful when return is needed inside nested logic.
- Test the example locally and verify the output matches the sample.
- Experiment by changing input values to see how behaviour changes.
Notes
- Semicolons at the end of statements are optional in Kotlin.