Lambda Expression and Anonymous Function in Kotlin

Tuğçe Aras
5 min readJul 8, 2023

--

Lambda Expression and Anonymous Function in Kotlin

Hi everyone 👋, our topic today is lambda expression and anonymous functions in Kotlin. I will talk about what they are, how they are used, etc. Let’s gets started then ✨

Before moving on to our topic, let’s briefly talk about functions. In Kotlin, functions are passed as first class citizens. What does that mean? 🤔

So let’s explain:
Functions ;

  • Can be assigned to variables,
  • It can be given as an argument,
  • It can be the return value of another function.

These items above meet the first class citizen requirements.

Lambda expression and anonymous functions are functions literal. So what exactly is functions literal? 🤔

Functions Literal : A structure that we assign a function to a variable is called. Kotlin provides us with 2 functions literals. These:

  • Lambda Expression
  • Anonymous Functions

Let’s start with the first.

🔶 Lambda Expression

  • Use curly braces.
  • Parameters are written in curly braces. Then this arrow sign (->) is put.
  • If the return type of the lambda expression is not Unit, the last expression in the lambda expression is considered the return type.
  • Lambda expressions are type inference .
  • Lambda expressions do not explicitly specify the return type.
url : lambda structure

Let’s look at the example lambda expression definitions then 👇

  • val myLambda : (parameters) -> returnType = {parameters-> body}
val info: (String, String) -> String = { name: String, surname: String -> "$name $surname"}
  • val myLambda : (parameters) -> noReturnType = {parameters-> body}
val info2 : (String, String) -> Unit= { name: String, surname: String -> println("$name $surname")}
  • val myLambda : (noParameters) -> noReturnType = {noParameters -> body}
val info3 : () -> Unit = {println("Hello World!")}
  • val myLambda : (noParameters) -> returnType = {noParameters -> body}
val info4 : () -> String = {"Hello Android Developers!"}
  • Let’s shorten the lambda expression syntax even more 😮
val info5 = {name:String, surname:String -> "$name $surname"}

So how do you think lambda expressions are kept in the background? Let’s see ✨

Let’s take the following code block as a base to examine.

val info: (String, String) -> String = { name: String, surname: String -> "$name $surname"}

Let’s look at show kotlin bytecode 👇

Kotlin ByteCode

NOTE : We also have the concept of Trailing Lambda. Let’s see what it is.

Trailing Lambda: If the last parameter of a function is also a function, the lambda expression passed as an argument can be written outside the parentheses. For example :

Trailing Lambda

NOTE : It is possible to explicitly return a value from a lambda with the Qualified return syntax. If not specified, the value is returned implicitly. So the lambda accepts the expression in the last line as its return value.

  • We can also write lambda expressions as destructuring declarations.

So like this: [Pay attention to the (name, age) part] ! 😉

val person = Pair("Elif", 24)

val printPerson: (Pair<String, Int>) -> Unit = { (name, age) ->
println("Name: $name, Age: $age")
}

Now let’s look at the Anonymous functions. 🥁🥁🥁

🔶 Anonymous Functions

  • It is similar to normal functions. Unlike normal functions,there is no function name. It is defined directly with the “fun” keyword.
  • With Anonymous functions, we can explicitly specify the return type.

So let’s see how it’s written 👇

val anonymousFunc = fun(number1:Int, number2:Int) : Int = number1 + number2
println(anonymousFunc(1,2))

Let’s see how it’s kept in the background then:

Kotlin ByteCode

NOTE : If Anonymous functions consist of a single expression body then the return type is automatically inferred. However, if the body of the function consists of more than one expression, then the return type must be specified explicitly.

What are the advantages of using anonymous functions? 🤔

  • It has short and simple syntax. It is especially suitable for one-time and simple operations.
  • Provides flexibility. Can be assigned to variables, returned from another function, or passed as arguments
  • It can be used easily with higher order functions.
  • Anonymous functions avoid name conflict problem.
  • It is a suitable structure for callback functions.

❗️❗❗️️ You can define an anonymous function even if you don’t provide a parameter or return value. This is a situation that totally depends on your needs. (Just like the definitions of lambda expression above)

Example has no parameter and no return value 👇

val myAnonymousFunc= fun(): Unit {
println("Hello Stranger!")
}
url: gif

--

--

Tuğçe Aras
Tuğçe Aras

Written by Tuğçe Aras

Android Developer at Şekerbank T.A.Ş. 💻💚 | https://bio.link/tugcearas

No responses yet