English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin Lambda Expression

Lambda expression

A lambda expression, or simply lambda, is an anonymous function; a function without a name. These functions are passed immediately as expressions without the need for declaration. For example,

fun main(args: Array<String>) {
    val greeting = { println("Hello!")}
    //Function call
    greeting()
}

When running this program, the output is:

Hello!

Here, the lambda expression is assigned to the variable greeting. This expression does not accept any parameters and does not return any value in this program.

Then, call the function (lambda expression) as follows:

greeting()

Example: Lambda with Parameters and Return Type

The following program has a lambda expression that accepts two integers as parameters and returns the product of the two integers.

fun main(args: Array<String>) {
    val product = { a: Int, b: Int -> a * b}
    val result = product(9, 3)
    println(result)
}

When running this program, the output is:

27

Here, the lambda expression is:

Please note that the curly braces contain a lambda expression.

Higher-order functions

Kotlin provides strong support for functional programming. You can pass a function as a parameter to other functions. Additionally, you can return a function from other functions. These features are called higher-order functions.

For convenience, lambda expressions are usually passed to higher-order functions (not typical functions).

Example: Passing Lambda to a Function

Let's pass the lambda expression to a higher-order function. This is your method of operation.

fun callMe(greeting: ()}} -> Unit) {
    greeting()
}
fun main(args: Array<String>) {
    callMe({ println("Hello!") })
}

When running this program, the output is:

Hello!

Here, callMe() is a higher-order function (because it takes a function as a parameter). The greeting parameter accepts a Lambda passed to the callMe() function:

 greeting: () -> Unit

Empty parentheses indicate that the passed anonymous function does not accept any parameters. And the Unit keyword indicates that the anonymous function does not return any value.

Lambda is often used when dealing with collections. And there are several built-in functions in the standard library that can use lambda to simplify our task in a more convenient way. You will see several examples here:

Example: maxBy() function

The maxBy() function returns the first element that produces the maximum value of the given function; if there are no elements, it returns null.

data class Person(val name: String, val age: Int)
fun main(args: Array<String>) {
    val people = listOf(
            Person("Jack", 34),}}
            Person("Shelly", 19),}}
            Person("Patrick", 13),}}
            Person("Jill", 12),}}
            Person("Shane", 22),}}
            Person("Joe", 18)
            )
    val selectedPerson = people.maxBy({ person -> person.age })
    println(selectedPerson)
    println("name:  ${selectedPerson?.name}"  )
    println("age:  ${selectedPerson?.age}"  )
}

When running this program, the output is:

Person(name=Jack, age=34)
name: Jack
age: 34

Here, the maxBy() function gets a list of Person objects and returns the Person object with the maximum age.

it keyword: used for single parameter

In the above program, the lambda expression only accepts one parameter (a list of Person objects). In this case, you can use the keyword it to refer to the parameter.

You can

val selectedPerson = people.maxBy({ person -> person.age })

Is equivalent to

val selectedPerson = people.maxBy({ it.age })

In the above program.

Example: maxBy() and startsWith() functions

The following program calculates the maximum age of the Person object that starts with the letter S.

We will use two library functions maxBy() and startsWith() to complete this task. If the startsWith() function is passed a specified character as a parameter and it starts with that character, it returns true.

data class Person(val name: String, val age: Int)
fun main(args: Array<String>) {
    val people = listOf(
            Person("Jack", 34),}}
            Person("Shelly", 19),}}
            Person("Patrick", 13),}}
            Person("Jill", 12),}}
            Person("Shane", 22),}}
            Person("Joe", 18)
            )
    val  selectedPerson  =  people
            .filter {  it.name.startsWith("S")  }
            .maxBy{  it.age  }
    println(selectedPerson)
    println("name:  ${selectedPerson?.name}"  )
    println("age:  ${selectedPerson?.age}"  )
}

When running this program, the output is:

Person(name=Shane,  age=22)
name:  Shane
age: 22