Unlock the Power of Lambda Expressions in Kotlin

What is a Lambda Expression?

Imagine a function without a name, passed as an expression without declaration. That’s what a lambda expression is – an anonymous function that can be used immediately.

val greeting = { println("Hello, World!") }
greeting()

This expression doesn’t accept any parameters and doesn’t return any value.

Lambda Expressions with Parameters and Return Types

But what if you need a lambda expression that takes parameters and returns a value? No problem!

val multiply = { a: Int, b: Int -> a * b }
val result = multiply(2, 3)
println(result) // Output: 6

The output will be the result of this calculation.

The Role of Curly Braces

Notice how the lambda expression is enclosed inside curly braces. This is a key aspect of lambda expressions in Kotlin.

Higher-Order Functions: The Key to Functional Programming

Kotlin shines when it comes to functional programming. You can pass functions as arguments to other functions, and even return a function from another function. These are called higher-order functions. Lambda expressions are often passed to higher-order functions for convenience.

Passing Lambda Expressions to Functions

Let’s see how you can pass a lambda expression to a higher-order function.

fun callMe(lambda: () -> Unit) {
    lambda()
}

callMe { println("Hello from lambda!") }

The callMe() function takes a lambda expression as a parameter, which is then invoked without any parameters or return values.

Working with Collections Made Easy

Lambda expressions are frequently used when working with collections. Kotlin’s standard library provides several built-in functions that take lambdas to make your task easier. Let’s explore a couple of examples:

The maxBy() Function

The maxBy() function returns the first element yielding the largest value of the given function or null if there are no elements.

data class Person(val name: String, val age: Int)

val people = listOf(Person("Alice", 25), Person("Bob", 30), Person("Charlie", 20))
val oldestPerson = people.maxBy { it.age }
println(oldestPerson?.name) // Output: Bob

In this program, maxBy() takes a list of Person objects and returns the Person object with the maximum age.

The it Keyword: A Shortcut for Single Parameters

When a lambda expression accepts only one parameter, you can refer to the argument using the it keyword. This simplifies your code and makes it more readable.

val names = people.map { it.name }
println(names) // Output: [Alice, Bob, Charlie]

Combining maxBy() and startsWith() Functions

Now, let’s compute the maximum age of a Person object starting with the letter S.

val peopleStartingWithS = people.filter { it.name.startsWith("S") }
val oldestPersonStartingWithS = peopleStartingWithS.maxBy { it.age }
println(oldestPersonStartingWithS?.name) // Output: Sam (assuming there is a Person named Sam)

We’ll use the maxBy() and startsWith() functions to achieve this. The startsWith() function returns true if the string starts with the specified character passed as an argument.

Leave a Reply