What is Anonymous Function in Kotlin: Simple Explanation and Example
anonymous function in Kotlin is a function without a name that can be defined and used directly. It allows you to write quick, inline functions especially useful for short tasks or passing as arguments.How It Works
Imagine you want to write a small task but don't want to give it a name because you only need it once. An anonymous function in Kotlin works like a quick note you write and use immediately without saving it as a file. It is a function that you define without a name and can use right where you need it.
Behind the scenes, Kotlin treats this function like any other, but since it has no name, you usually assign it to a variable or pass it directly as an argument to another function. This makes your code cleaner and easier to read when the function is simple and used only in one place.
Example
This example shows an anonymous function assigned to a variable and then called to add two numbers.
val sum = fun(a: Int, b: Int): Int {
return a + b
}
fun main() {
println(sum(5, 3))
}When to Use
Use anonymous functions when you need a small piece of code to perform a task just once or pass it as a quick action to another function. For example, when sorting a list or handling a button click, anonymous functions let you write the logic inline without cluttering your code with many named functions.
This is helpful in event handling, callbacks, or any place where a short, simple function is needed temporarily.
Key Points
- Anonymous functions have no name and are defined with the
funkeyword. - They can be assigned to variables or passed as arguments.
- Useful for short, one-time tasks or inline logic.
- Different from lambda expressions but serve similar purposes.