Skip to main content
ubuntuask.com

Back to all posts

How to Work With Lambdas In Kotlin?

Published on
6 min read
How to Work With Lambdas In Kotlin? image

Best Kotlin Programming Books to Buy in October 2025

1 Head First Kotlin: A Brain-Friendly Guide

Head First Kotlin: A Brain-Friendly Guide

BUY & SAVE
$50.36 $79.99
Save 37%
Head First Kotlin: A Brain-Friendly Guide
2 Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language

Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language

BUY & SAVE
$33.00 $38.99
Save 15%
Android Programming with Kotlin for Beginners: Build Android apps starting from zero programming experience with the new Kotlin programming language
3 Kotlin in Action, Second Edition

Kotlin in Action, Second Edition

BUY & SAVE
$45.98 $59.99
Save 23%
Kotlin in Action, Second Edition
4 Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin

BUY & SAVE
$59.30 $89.99
Save 34%
Head First Android Development: A Learner's Guide to Building Android Apps with Kotlin
5 Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines

BUY & SAVE
$48.00 $65.99
Save 27%
Programming Android with Kotlin: Achieving Structured Concurrency with Coroutines
6 Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

BUY & SAVE
$29.95 $32.95
Save 9%
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)
7 Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer

Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer

BUY & SAVE
$36.20 $59.99
Save 40%
Kotlin from Scratch: A Project-Based Introduction for the Intrepid Programmer
8 Kotlin: An Illustrated Guide

Kotlin: An Illustrated Guide

BUY & SAVE
$49.62
Kotlin: An Illustrated Guide
9 Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices

Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices

BUY & SAVE
$30.53 $44.99
Save 32%
Kotlin Design Patterns and Best Practices: Elevate your Kotlin skills with classical and modern design patterns, coroutines, and microservices
10 Kotlin in Action

Kotlin in Action

BUY & SAVE
$34.71 $44.99
Save 23%
Kotlin in Action
+
ONE MORE?

Lambdas in Kotlin are used to create anonymous functions, known as function literals. They are function types that can be stored in variables, passed as arguments to other functions, or returned from functions.

To work with lambdas in Kotlin, you need to follow a few steps:

  1. Define a Lambda: Lambda expressions are defined using curly braces { }. You can specify the input parameters, separated by commas, before the arrow (->), followed by the expression or block of code you want to execute. For example, a lambda that calculates the sum of two numbers can be defined as { a, b -> a + b }.
  2. Store a Lambda: You can assign a lambda expression to a variable. The variable should have a function type that matches the lambda's signature. For example, you can define a variable sum of function type (Int, Int) -> Int and assign the lambda mentioned above to it.
  3. Invoke a Lambda: To execute a lambda, you simply invoke it as if it were a regular function, using the variable name followed by parentheses. For example, to invoke the sum lambda, you can call sum(3, 5), which will return the sum of 3 and 5.
  4. Pass a Lambda as an Argument: Lambdas can be passed as arguments to other functions. Functions that expect a lambda parameter typically declare it using a function type. For example, you might have a higher-order function performOperation that takes two numbers and a lambda expression as arguments, and performs the operation specified by the lambda.
  5. Use lambda in Collection Operations: Lambdas are commonly used in collection operations like filter, map, reduce, etc. These operations can be performed on lists, arrays, sets, and other collections to manipulate or transform the data. For example, the filter function takes a lambda that determines the filtering condition, and it returns a new list containing only the elements that satisfy the condition.

Working with lambdas in Kotlin enables you to write more concise and expressive code by reducing the need for named functions or interfaces. They provide a flexible mechanism to pass behavior as data and can greatly enhance the readability and functionality of your programs.

How to use a lambda with Kotlin's when expression?

To use a lambda with Kotlin's when expression, you can pass the lambda as an argument to the when statement.

Here's an example:

val number = 5

when (number) { in 1..10 -> { println("Number is between 1 and 10") } { it % 2 == 0 } -> { println("Number is even") } else -> { println("Number is not in the specified range or it is not even") } }

In the above example, we use two different lambda expressions within the when expression.

The first lambda expression in 1..10 checks if the number is in the range from 1 to 10.

The second lambda expression { it % 2 == 0 } checks if the number is even.

If any of the conditions in the when expression evaluates to true, the corresponding block of code will be executed. If none of the conditions match, the else block will be executed.

What are the implicit and explicit label returns in Kotlin lambdas?

In Kotlin lambdas, the implicit label return refers to the value of the last expression inside the lambda block. It means that the value of this expression will be automatically returned from the lambda function.

For example, if you have a lambda that calculates the sum of two numbers:

val sum: (Int, Int) -> Int = { a, b -> a + b }

In this case, the implicit label return will be the value of the expression a + b, so the lambda will return the sum of the two given numbers.

On the other hand, the explicit label return is used when you want to explicitly define the return value within the lambda block. It is done using the return keyword and specifying the value to be returned.

For example:

val multiply: (Int, Int) -> Int = { a, b -> val result = a * b return@multiply result }

In this case, the explicit label return return@multiply is used to indicate that the value of the variable result should be returned from the lambda when it is invoked.

In most cases, the implicit label return is sufficient for returning values from lambdas, but the explicit label return can be useful in more complex scenarios where you want to specify the exact return point.

How to use a lambda as an argument in the filter function?

To use a lambda as an argument in the filter function, follow these steps:

  1. Define your lambda expression inside the filter function. The general syntax of a lambda expression is lambda arguments: expression.
  2. Specify the sequence or iterable you want to filter as the first argument to the filter function. This can be a list, tuple, set, or any other iterable object.
  3. Use the lambda expression as the second argument to the filter function. The lambda expression will determine which elements of the sequence will be included in the filtered output. It should evaluate to a boolean value, where True indicates that the element should be included, and False indicates exclusion.
  4. Obtain the filtered output by converting the filter object to a list or iterating over it. The filter function returns an iterator object that contains the elements satisfying the lambda condition. You can use the list() function to convert it to a list or iterate over it using a loop.

Here's an example that demonstrates how to use a lambda as an argument in the filter function:

numbers = [1, 2, 3, 4, 5, 6]

Filter out the even numbers using a lambda expression

filtered_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print(filtered_numbers) # Output: [2, 4, 6]

In this example, the lambda expression lambda x: x % 2 == 0 checks if a number is even by evaluating the condition x % 2 == 0. The filter() function filters out the numbers for which this condition is False, resulting in a list of even numbers.

How to assign a lambda to a variable in Kotlin?

In Kotlin, you can assign a lambda function to a variable by using the val keyword followed by the variable name, then the = sign, and finally the lambda expression. Here's an example:

val square: (Int) -> Int = { number -> number * number }

In the above example, square is the variable name, (Int) -> Int represents the function type that takes an Int as input and returns an Int as output, and { number -> number * number } is the lambda expression.

You can then use the variable square like any other function. Here's an example of calling the lambda function:

val result = square(5) // calling the lambda function with input 5 println(result) // output: 25

In this case, result will be assigned the value returned by the square lambda function, which is 25.