Working with Anonymous Function in Kotlin
Last Updated :
21 Jun, 2025
In Kotlin, we can treat functions as expressions by creating lambdas. A lambda is a function literal, meaning it’s a function that doesn’t have a name and is defined directly as an expression. These lambda expressions can also be passed as parameters to other functions. However, one important thing to remember is that in lambdas, we cannot explicitly declare the return type. Usually, the Kotlin compiler is smart enough to figure out the return type on its own. But in some cases, when the return type cannot be inferred or when we want to be very clear and specify it explicitly, we can use anonymous functions instead. In this article, we’ll explore what anonymous functions are, how they are different from lambdas, and how to use them effectively in Kotlin.
Prerequisites for this Article
Before we start, make sure you have a basic understanding of:
- Functions in Kotlin
- Lambda Expressions (short way to define a function)
- Anonymous Functions (an alternative way to define a function)
Refer to this article: Lambdas Expressions and Anonymous Functions
Lambda Expressions in Kotlin -
Let’s first see how to create and use a lambda:
Kotlin
// Lambda to multiply two numbers
val funMultiply = { a: Int, b: Int -> a * b }
// Lambda to print a greeting
val funSayHi = { name: String -> println("Hi, $name!") }
In the example above funMultiply takes two integers and returns their product and funSayHi takes a string and prints a greeting message. Notice that we did not specify return types, Kotlin automatically figures them out.
Anonymous Functions
Sometimes, we want or need to explicitly define the parameter types or return type. For such situations, Kotlin provides anonymous functions. An anonymous function is just like a regular function but without a name.
Example:
Kotlin
val funMultiply = fun(a: Int, b: Int): Int {
return a * b
}
In this example we used the fun keyword to define an anonymous function. The parameter types (a: Int, b: Int) and the return type Int are explicitly declared. The function returns the product of a and b. This form is useful when we want to make sure the return type is clearly stated, especially when the compiler cannot infer it.
Passing Anonymous Functions to Higher Order Functions
So now we have a general idea of how anonymous functions work. Now, let's try and pass one in another function-that is, we will try a high-order function. Check out this code snippet:
Kotlin
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val result = operateOnNumbers(5, 10, fun(x: Int, y: Int): Int {
return x + y
})
println("The result is: $result")
Output:
The result is: 15
Here operateOnNumbers is a higher-order function, it takes another function as a parameter. We passed an anonymous function as the third argument and the anonymous function performs addition on two numbers.
Differences Between Lambda Expressions and Anonymous Functions
Lambdas | Anonymous Functions |
Cannot explicitly declare return type. | Can explicitly declare return type. |
The return statement returns from the enclosing function (if used inside another function). | The return statement returns only from the anonymous function itself. |
Parameters can be outside parentheses or even omitted (using it). | Parameters are always written inside parentheses. |
Usually shorter and used for simple operations. | Useful for more complex or clear function definitions. |
Example:
Kotlin
fun testLambda() {
val lambda = { return } // returns from testLambda
lambda()
println("This line is unreachable")
}
fun testAnonymousFunction() {
val anonFunc = fun() { return } // returns only from anonymous function
anonFunc()
println("This line is reachable") // this will be printed
}
Similar Reads
Transform a List Using Map Function in Kotlin Kotlin is a statically typed, general-purpose programming language developed by JetBrains, that has built world-class IDEs like IntelliJ IDEA, PhpStorm, Appcode, etc. It was first introduced by JetBrains in 2011 and is a new language for the JVM. Kotlin is an object-oriented language, and a âbetter
3 min read
Suspend Function In Kotlin Coroutines Prerequisite: Kotlin Coroutines on Android The Kotlin team defines coroutines as âlightweight threadsâ. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a
4 min read
How to Write swap Function in Kotlin using the also Function? Swapping two numbers is one of the most common tasks in programming. Usually, when we swap two values in languages like Java or C++, we either use a third temporary variable or pointers/references to perform the swap. In Java, since we donât have pointers, we almost always rely on a third variable t
3 min read
Kotlin Function Variations With Examples In Kotlin, while defining a function, we have many optional features and variations that make functions more flexible and easier to use. In this article, weâll go through these different ways of defining functions one by one, using simple explanations and examples.Function DefinitionHere is the stan
3 min read
Passing Variable Arguments to a Function in Kotlin There are a lot of scenarios in which we need to pass variable arguments to a function. In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T
4 min read