Lambda Functions in Kotlin
A lambda function in Kotlin is a concise way to define an anonymous function. It is a function literal
(a function without a name) that can be passed as a parameter or stored in a variable. Lambdas
improve code readability and reduce boilerplate when working with higher-order functions.
■ Uses of Lambda Functions:
1. Callbacks: Pass logic directly as a function parameter.
2. Collection Operations: Used in map, filter, reduce, forEach.
3. Event Handling: Replace verbose listener interfaces with inline logic.
4. Short Reusable Functions: Store and reuse small chunks of behavior.
5. Functional Programming: Enable writing clean and concise functional-style code.
■ Example:
fun main() { // Lambda assigned to a variable val square: (Int) -> Int = { x -> x * x
} println(square(5)) // Output: 25 // Using lambda in collection operation val
numbers = listOf(1, 2, 3, 4, 5) val doubled = [Link] { it * 2 }
println(doubled) // Output: [2, 4, 6, 8, 10] }