Google News
logo
Kotlin - Interview Questions
What is a lambda expression in Kotlin?
In Kotlin, a lambda expression is a concise way to define anonymous functions, also known as function literals. It allows you to create small, inline functions without explicitly declaring a function name. Lambda expressions are particularly useful when working with higher-order functions, functional programming, or when you need to pass behavior as an argument.

Here are some key points about lambda expressions :

1. Syntax : The syntax of a lambda expression consists of a parameter list, followed by the arrow (`->`), and then the body of the function.
   val lambdaName: (ParameterType) -> ReturnType = { parameter ->
       // Function body
       // ...
   }​

2. Parameter List : The parameter list defines the input parameters for the lambda expression. It can be empty or contain one or more parameters. If there is only one parameter, you can omit the parameter list and refer to it as `it` within the lambda body.
   val double: (Int) -> Int = { number ->
       number * 2
   }

   val square: (Int) -> Int = { it * it }​

3. Arrow (`->`) : The arrow separates the parameter list from the body of the lambda expression. It indicates the start of the function body.
4. Function Body : The function body contains the code that is executed when the lambda expression is invoked. It can be a single expression or a block of multiple statements. If it's a block, the last expression is treated as the return value.
   val sum: (Int, Int) -> Int = { a, b ->
       val result = a + b
       result // Last expression is the return value
   }

   val greet: () -> Unit = {
       println("Hello, World!")
   }​

5. Type Inference : In many cases, Kotlin can infer the types of lambda parameters and return values, so you don't need to explicitly declare them. However, you can provide explicit type annotations when necessary.

6. Lambda as Arguments : Lambda expressions are often used as arguments for higher-order functions, which are functions that take other functions as parameters. This enables powerful functional programming constructs like map, filter, reduce, etc.
   val numbers = listOf(1, 2, 3, 4, 5)

   val doubled = numbers.map { it * 2 }

   val evenNumbers = numbers.filter { it % 2 == 0 }

   val sum = numbers.reduce { acc, number -> acc + number }​
Lambda expressions provide a concise and flexible way to define anonymous functions in Kotlin. They are commonly used in functional programming, for defining behavior inline, and as arguments for higher-order functions. Lambda expressions make code more expressive and allow for more concise and readable functional-style programming constructs.
Advertisement