0
0
KotlinConceptBeginner · 3 min read

What is Anonymous Function in Kotlin: Simple Explanation and Example

An 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.

kotlin
val sum = fun(a: Int, b: Int): Int {
    return a + b
}

fun main() {
    println(sum(5, 3))
}
Output
8
🎯

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 fun keyword.
  • 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.

Key Takeaways

Anonymous functions in Kotlin are unnamed functions used for quick, inline tasks.
They help keep code clean by avoiding unnecessary named functions for simple actions.
You can assign anonymous functions to variables or pass them directly as arguments.
Ideal for event handling, callbacks, and short-lived logic.
They differ from lambdas but both simplify function usage.