Kotlin Let vs Run: A Comparative Analysis
In the realm of functional programming, Kotlin provides two powerful tools for working with collections: `let` and `run`. Both are higher-order functions that allow you to perform operations on a receiver object, but they have distinct use cases and syntax. Let's delve into the details of `let` and `run`, understand their differences, and explore when to use each.
Understanding Kotlin Let
`let` is a Kotlin extension function that takes a lambda as an argument and returns the result of the lambda's last expression. It's primarily used for performing operations on a receiver object and returning a result. Here's the basic syntax:
receiver.let { it -> /* lambda body */ }
The `it` keyword refers to the receiver object. Here's an example:

data class Person(val name: String, val age: Int)
fun main() {
val person = Person("Alice", 30)
val (name, age) = person.let { it.name to it.age }
println("Name: $name, Age: $age")
}
Understanding Kotlin Run
`run` is another Kotlin extension function that also takes a lambda as an argument. However, it returns the receiver object itself, making it useful for chaining method calls. Here's the basic syntax:
receiver.run { /* lambda body */ }
In the `run` block, you can access the receiver object using the `this` keyword. Here's an example:
data class Person(val name: String, var age: Int)
fun main() {
val person = Person("Bob", 25)
person.run {
this.age++
println("Name: $name, Age: $age")
}
}
Let vs Run: Key Differences
- Return Type: `let` returns the result of the lambda's last expression, while `run` returns the receiver object itself.
- Receiver Access: In `let`, you access the receiver using `it`, while in `run`, you use `this`.
- Use Cases: `let` is often used for transforming data or performing operations that result in a new value. `run` is used for performing side effects on the receiver object or chaining method calls.
When to Use Let and Run
Here's a table to help you decide when to use `let` and `run`:

| Use Case | let | run |
|---|---|---|
| Transforming data | ✅ | ❌ |
| Performing side effects | ❌ | ✅ |
| Chaining method calls | ❌ | ✅ |
In conclusion, `let` and `run` are powerful tools in Kotlin that allow you to work with collections and objects in a concise and expressive way. Understanding their differences and use cases will help you write more idiomatic and readable Kotlin code.























