Lambdas in Kotlin are a convenient way to write concise and functional code by creating anonymous functions. They allow you to treat functions as variables, which means you can pass them as arguments to other functions or assign them to variables directly.
To create a lambda function in Kotlin, you use the { }
notation. Inside the curly braces, you define the parameters (if any) and the body of the lambda.
Here is a simple example of a lambda expression that multiplies two numbers and returns the result:
1
|
val multiply: (Int, Int) -> Int = { a, b -> a * b }
|
In this example, multiply
is a variable of type (Int, Int) -> Int
, which means it is a function that takes two integer parameters and returns an integer. The lambda expression { a, b -> a * b }
defines the actual implementation of the function.
To use the lambda, you can invoke it like a regular function:
1
|
val result = multiply(2, 4) // result will be 8
|
Lambdas are commonly used when working with higher-order functions like map
, filter
, and reduce
. These functions accept other functions (or lambdas) as parameters to customize their behavior.
For example, the map
function takes a lambda that defines how each element of a collection should be transformed:
1 2 |
val numbers = listOf(1, 2, 3, 4, 5) val squaredNumbers = numbers.map { it * it } // [1, 4, 9, 16, 25] |
In this case, the lambda { it * it }
defines how each element it
of the numbers
list should be squared.
Lambdas can capture variables from their surrounding scope. This means they can access and modify variables defined outside of their own body. This behavior is called "variable capturing" or "closure."
1 2 3 4 5 6 7 8 |
var factor = 2 val multiplyByFactor: (Int) -> Int = { number -> number * factor } //... val result = multiplyByFactor(5) // result will be 10 factor = 3 val updatedResult = multiplyByFactor(5) // updatedResult will be 15 |
In this example, the lambda multiplyByFactor
captures the factor
variable and multiplies the passed number by it. When factor
changes, the lambda automatically uses its updated value.
How to use lambda expressions with collections in Kotlin?
Lambda expressions can be used with collections in Kotlin using various higher-order functions like map
, filter
, forEach
, reduce
, etc. Here's how you can use lambda expressions with collections:
- map: The map function is used to transform each element of a collection based on a lambda expression and returns a new collection with the transformed elements.
1 2 3 |
val numbers = listOf(1, 2, 3, 4, 5) val squaredNumbers = numbers.map { it * it } println(squaredNumbers) // Output: [1, 4, 9, 16, 25] |
- filter: The filter function is used to select elements from a collection based on a condition specified through a lambda expression. It returns a new collection with the filtered elements.
1 2 3 |
val numbers = listOf(1, 2, 3, 4, 5) val evenNumbers = numbers.filter { it % 2 == 0 } println(evenNumbers) // Output: [2, 4] |
- forEach: The forEach function is used to perform an operation on each element of a collection using a lambda expression.
1 2 |
val numbers = listOf(1, 2, 3, 4, 5) numbers.forEach { println(it) } // Output: 1 2 3 4 5 |
- reduce: The reduce function is used to combine the elements of a collection using a lambda expression and returns the accumulated result.
1 2 3 |
val numbers = listOf(1, 2, 3, 4, 5) val sum = numbers.reduce { acc, num -> acc + num } println(sum) // Output: 15 |
These are just a few examples of how lambda expressions can be used with collections in Kotlin. Kotlin provides a wide range of higher-order functions that can be utilized to operate on collections using lambda expressions.
What is a lambda expression in Kotlin?
In Kotlin, a lambda expression is a concise way to define an anonymous function without a name. It can be thought of as a function literal that can be passed around and executed later.
A lambda expression is typically used for functional programming constructs like higher-order functions, which take one or more functions as arguments or return a function as a result. The lambda expression allows you to define and pass functions directly as arguments to other functions, without explicitly declaring them.
The basic syntax of a lambda expression in Kotlin is as follows:
val lambdaVariableName: (parameterTypes) -> returnType = { parameters -> expression }
Here,
- lambdaVariableName is the name of the variable that holds the lambda expression.
- parameterTypes denote the parameter types the lambda expression takes.
- returnType specifies the return type of the lambda expression.
- parameters represent the names of the parameters passed to the lambda expression.
- expression is the body of the lambda expression, which may return a value or perform some computation.
For example, a lambda expression to compute the square of a number can be written as:
val square: (Int) -> Int = { x -> x * x }
Here, 'square' is the variable name for the lambda expression, '(Int) -> Int' denotes that it takes an integer as input and returns an integer, and '{ x -> x * x }' is the body of the lambda expression that squares the input 'x'.
How to convert a lambda to a functional interface in Kotlin?
In Kotlin, a lambda expression can be converted to a functional interface using the SAM (Single Abstract Method) conversion, which allows treating a lambda as an instance of a functional interface. Here's an example of how to convert a lambda to a functional interface in Kotlin:
Step 1: Define a functional interface
1 2 3 |
interface MyFunctionalInterface { fun doSomething(value: Int) } |
Step 2: Assign a lambda to a variable of the functional interface type
1 2 3 |
val myLambda: MyFunctionalInterface = { value -> println("Lambda value: $value") } |
In this step, we assign a lambda expression to a variable myLambda
of type MyFunctionalInterface
. The lambda accepts an Int
, prints a message using the value, and doesn't have a return value.
Step 3: Call the lambda function
1
|
myLambda.doSomething(5)
|
Now, you can call the doSomething()
function on myLambda
and pass an Int
value.
The output will be:
1
|
Lambda value: 5
|
By following these steps, you can convert a lambda to a functional interface in Kotlin.