A Beginner’s Guide to Kotlin Lambdas

Kotlin is a modern programming language that runs on the Java Virtual Machine (JVM). It offers many powerful features, including support for functional programming. One of the key features of functional programming in Kotlin is lambdas. Lambdas allow you to write concise and expressive code by treating functions as first-class citizens.

Table of Contents:

  1. What are Lambdas?
  2. Syntax of Lambdas
  3. Using Lambdas with Functional Interfaces
  4. Lambda Expression vs. Anonymous Function
  5. Higher-Order Functions
  6. Capturing Variables in Lambdas
  7. Built-in Higher-Order Functions

1. What are Lambdas?

Lambdas, also known as anonymous functions, are functions without a name that can be passed around as values. In Kotlin, lambdas are defined using a syntax that is concise and easy to read. They allow you to create functions on-the-fly and pass them as arguments to other functions.

2. Syntax of Lambdas

The syntax of a lambda expression in Kotlin consists of the function parameter list, an arrow ->, and the body of the function. Here’s an example:

val sum: (Int, Int) -> Int = { x, y -> x + y }

In this example, sum is a lambda that takes two Int parameters and returns their sum. The type of the lambda is explicitly specified as (Int, Int) -> Int.

3. Using Lambdas with Functional Interfaces

  1. Kotlin provides functional interfaces like Predicate, Consumer, and Supplier that are compatible with lambdas. These interfaces define common functional operations and can be used with Lambdas to perform various tasks.

Here’s an example of using lambda with the Predicate interface:

val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }

In this example, the lambda { it % 2 == 0 } is used with the filter function to retrieve only the even numbers from the list.

4. Lambda Expression vs. Anonymous Function

In Kotlin, there are two ways to define a lambda: using a lambda expression or an anonymous function. While both can achieve the same result, they have some differences in syntax and behaviour.

A lambda expression is the most common way to define a lambda, as shown in the previous examples. It has a concise syntax and can access variables from its surrounding scope.

On the other hand, an anonymous function has a more explicit syntax and allows you to specify the return type. It behaves like a regular function and can have multiple return statements.

5. Higher-Order Functions

  1. Higher-order functions are functions that can accept other functions as parameters or return them as results. Kotlin’s support for lambdas makes it easy to define and use higher-order functions.

Here’s an example of a higher-order function that takes a lambda as a parameter:

fun operateOnNumbers(x: Int, y: Int, operation: (Int, Int) -> Int): Int {
    return operation(x, y)
}

val result = operateOnNumbers(5, 3) { a, b -> a * b }

In this example, the operateOnNumbers function accepts a lambda as the operation parameter. The lambda multiplies the two numbers and returns the result.

6. Capturing Variables in Lambdas

Lambdas can capture variables from their surrounding scope. This means that they can access and modify variables that are defined outside of their own body.

Here’s an example that demonstrates variable capturing in lambdas:

fun createIncrementer(incrementBy: Int): () -> Int {
    var counter = 0
    return {
        counter += incrementBy
        counter
    }
}

val incrementByTwo = createIncrementer(2)
println(incrementByTwo()) // Output: 2
println(incrementByTwo()) // Output: 4

In this example, the createIncrementer function returns a lambda that increments a counter by the specified value. The lambda captures the counter variable and remembers its state between invocations.

7. Built-in Higher-Order Functions

Kotlin provides several built-in higher-order functions, such as map, filter, and reduce. These functions operate on collections and allow you to perform common operations in a concise and functional way.

Here’s an example that demonstrates the use of the map function:

val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }

In this example, the map function applies the lambda { it * it } to each element in the numbers list, resulting in a new list with squared numbers.

In this tutorial, we explored Kotlin lambdas and learned how to use them effectively. We covered the syntax of lambdas, using lambdas with functional interfaces, higher-order functions, capturing variables in lambdas, and built-in higher-order functions. Lambdas are a powerful feature of Kotlin that enables you to write expressive and concise code.

Some Important Links:

Kotlin Roadmap 2023

Kotlin Lambda Official Documentation Link

Happy Composing 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *