What is Lambda in Kotlin: Simple Explanation and Examples
lambda is a small block of code that can be passed around and executed later, similar to a function without a name. It allows you to write concise and flexible code by treating behavior as a value.How It Works
Think of a lambda in Kotlin as a mini-function that you can write right where you need it, without giving it a name. It’s like writing a quick instruction note that you can hand off to someone else to use whenever they want. This makes your code more flexible and easier to read.
Under the hood, a lambda is an object that implements a function interface. You can pass it as an argument to other functions, store it in variables, or return it from functions. This lets you customize behavior dynamically, like choosing different actions based on conditions.
Example
This example shows a lambda that adds two numbers and prints the result. The lambda is stored in a variable and then called like a function.
fun main() {
val add: (Int, Int) -> Int = { a, b -> a + b }
val result = add(5, 3)
println("Sum is $result")
}When to Use
Use lambdas when you want to pass a small piece of code as a parameter, like for sorting, filtering, or handling events. They are great for making your code shorter and clearer, especially when working with collections or asynchronous tasks.
For example, you can use lambdas to define what happens when a button is clicked in an app, or to specify how to transform a list of items without writing a full function each time.
Key Points
- Lambdas are anonymous functions that can be stored and passed around.
- They help write concise and flexible code.
- Commonly used with collections and event handling.
- Syntax uses curly braces with parameters and an arrow.