All the different types of functions we saw in the last article are called named functions. Kotlin allows us to define functions without a name as well and these types of functions are called anonymous functions.
Anonymous Functions
An anonymous function has no name as part of its definition, and it interacts with the rest of your code a little differently in that it is commonly passed to or returned from other functions.
Anonymous functions allows you to customize the standard library functions to meet your needs.
val string = "Mississippi"
val numLetters = string.count({ letter ->
letter == 's'
})
Don’t stress too much about what each line means here. We’ll go into its details one by one.
Just like a named function, an anonymous function does its work only when it has been called, using parentheses along with any arguments the function expects.
Function Types
Anonymous functions also have a type, called the function type. These types have a special notation that corresponds to the signature of the functions.
- It consists of two parts: function parameters in parentheses followed by its return types, delimited by the arrow ( -> ).
(A, B) -> Cdenotes a type that represents functions that take two arguments of typesAandBand return a value of typeC. The list of parameter types may be empty, as in() -> A. TheUnitreturn type cannot be omitted.

- Function types can optionally have an additional receiver type, which is specified before the dot in the notation: the type
A.(B) -> Crepresents functions that can be called on a receiver objectAwith a parameterBand return a valueC. Function literals with receiver are often used along with these types.

- Suspending functions belong to a special kind of function type that have a suspend modifier in their notation, such as
suspend () -> Unitorsuspend A.(B) -> C.
We will go in more details about suspend functions in the future articles.
The function type notation can optionally include names for the function parameters: (x: Int, y: Int) -> Int. These names can be used for documenting the meaning of the parameters.
To specify that a function type is nullable, use parentheses as follows:
((Int, Int) -> Int)?.
Instantiating a function type
There are multiple ways to get an instance of a function type:
- By creating anonymous functions in either of the following ways:
val greeting : () -> String = {
val language = "Kotlin"
"Introduction to $language"
}
val multiply : (Int, Int) -> Int = fun(a: Int, b: Int): Int = a * b
fun main(){
greeting() //Output will be "Introduction to Kotlin"
multiply(2, 3) //Output will be 6
}
2. Using a callable reference to an existing declaration

inc, minus, uppercase are Kotlin’s functions and here we are creating our own instances of them
3. Use instances of a custom class that implements a function type as an interface

Implicit Returns
Unlike a named function, an anonymous function does not require or even allow except in rare cases the return keyword to output data. Instead, it implicitly returns the last line of the function definition allowing you to omit the return keyword.
This feature is both a convenience and a necessity of the anonymous functions syntax because it could be ambiguous to the compiler which function the return is from: the function the anonymous function was invoked within or the anonymous function itself.
The it keyword
When defining anonymous functions that accept exactly one argument , the it keyword is available as a convenient alternative to specifying the parameter name.
it is great for shorter expressions where the logic is clear without an argument name. But, when you are working with more complex function definitions, or with nested anonymous functions, you should stick with naming the parameter to preserve future readers and your own sanity.
val greeting: (String) -> Unit = {
println("Hello $it")
}
val greeting: (String) -> Unit = { name ->
println("Hello $name")
}
Type Inference Support
Kotlin’s type inference rules behave exactly the same with function types as they do with the other types.

For the compiler to infer the type of the anonymous function (function type), you do need to provide both the name and the type of each parameter in the anonymous function definition.
When combined with an ambiguous implicit return type, type inference may make an anonymous function difficult to read. But when your anonymous function is simple and clear, type inference is an asset for making your code more concise.
Terminology
Anonymous functions are referred as lambdas and their definitions as lambda expressions. And what an anonymous functions returns is called a lambda result.
Underscore for unused variables
If a lambda parameter is unused, you can replace its name with an underscore (_)
val greeting: (String) -> Unit = { _ ->
println("Hello Everyone")
}
Higher Order Functions
A function that takes functions as parameters or returns a function is called a higher-order function.
A commonly used example showcasing the usage of passing a function as a parameter occurs when we aim to associate a specific function with the click event of a view.
fun bindTextView(name: String, onClick: () -> Unit){
textView.setText("Hi $name")
textView.setOnClickListener(onClick())
}
fun main(){
bindTextView("Tanya"){
showToast("We called a higher order function")
}
}
Here’s another example of a higher-order function: returning a function itself.
fun createMultiplier(multiplier: Int): (Int) -> Int {
return { number -> number * multiplier }
}
fun main(){
val multiplyByTwo = createMultiplier(2)
val result = multiplyByTwo(5) // Call the returned function with input 5
println(result) // Output: 10
}
In this example, we have a higher-order function called createMultiplier. It takes an integer multiplier as a parameter and returns a function that multiplies a given number by the multiplier.
Summary points:
- Anonymous functions in Kotlin provide a flexible way to define functions without a name.
- They can be passed as arguments or returned as values.
- Function types have a special notation representing the signature of the functions, which can include receiver types and support suspending functions.
- You can instantiate function types in different ways.
- Implicit returns and the “it” keyword make anonymous functions concise.
- Kotlin’s type inference applies to function types.
- Anonymous functions are often called lambdas, and higher-order functions enhance code modularity and reusability.
- By understanding and using them, you can write expressive and efficient code in Kotlin.
That’s it for this article. Hope it was helpful! If you like it, please hit like.
Other articles of this series:
