In Kotlin, a lambda expression is a function literal that can be used as an anonymous function. A lambda expression is defined using curly braces containing the function body, and the input parameters (if any) are listed before the function body, separated by a arrow ->. For example:
val square: (Int) -> Int = { x -> x * x }
This lambda expression defines a function that takes an Int as input and returns the square of that number as an Int. The variable ‘square‘ has a functional type that represents a function of one Int input and one Int output.
Lambdas are often used in Kotlin in conjunction with higher-order functions. A higher-order function is a function that takes one or more functions as input and/or returns a function as output. For example:
fun applyOperation(x: Int, operation: (Int) -> Int): Int {
return operation(x)
}
val result = applyOperation(5, { x -> x * x })
//result = 25
In this example, the ‘applyOperation‘ function takes two arguments: an Int ‘x‘ and a function of type ‘(Int) -> Int‘ called ‘operation‘. The function ‘applyOperation‘ simply applies the ‘operation‘ function to the input ‘x‘ argument and returns the result.
The variable ‘result‘ is assigned the value returned by the call to ‘applyOperation‘ with the input arguments ‘5‘ and a lambda expression that defines the ‘operation‘ function. In this case, the lambda expression is ‘ x -> x * x ‘, which is the same lambda expression we defined earlier to represent the ‘square‘ function.
Lambdas make it easy to define and pass functions around as first-class objects in Kotlin, allowing for greater flexibility and modularity in code design.