Difference Between Let and Run Kotlin Scope Functions | Mastering Scope Functions in Kotlin

Puneet Grover
3 min readMay 10, 2023

Kotlin provides us with five scope functions to perform operations on an object and return the result in a concise and expressive way.

Two of these scope functions are let and run. Although they both allow us to perform operations on an object and return a new value, there are some key differences between them.

Let’s explore the differences between let and run with some examples. First, let’s see an example of let:

val str = "Hello, World!"
val result = str.let {
it.length // Perform operations on the object
}
println(result) // Output: 13

Now, let's see an example of run:

val str = "Hello, World!"
val result = str.run {
length // Perform operations on the object
}
println(result) // Output: 13

In both examples, we perform some operations on the string str.

The main difference between let and run is that let takes the object as an argument and returns the result of the lambda expression, while run takes the object as the context and returns the result of the lambda expression.

In other words, because let takes the object as an argument, then it returns a new value based on the object and the operations performed on it, while run takes the object as the context directly that means run modifies the original object and returns it

If you don’t need to modify the original object and just want to perform some operations on it and get a new value, let is a good choice.

On the other hand, if you need to modify the original object and get the modified object itself as the result, run is a better choice.

Let’s see another example of run to understand its usage better.

  • Suppose we have a mutable list of integers, and we want to remove all the even numbers from it. We can use run to modify the list in place and return the modified list itself:
val numbers = mutableListOf(1, 2, 3, 4, 5, 6)
numbers.run {
removeAll { it % 2 == 0 } // modify the list in place
this // return the modified list itself
}
println(numbers) // Output: [1, 3, 5]

In this example, we use run to modify the numbers list in place by removing all the even numbers from it. We pass the lambda expression to run that performs this operation on the list, and then returns the modified list itself by referencing it with this. The result of the run function is the modified list itself.

To summarize:-

let is useful when we want to chain operations on an object or perform operations on an object only if it’s not null. On the other hand, run is useful when we want to modify an object in place and use the modified object immediately.

Watch Video ▶️ On My Youtube Channel “CodingWithPuneet”

Like | Share | Subscribe for more such Relatable Content.

Keep Learning, Happy Coding!

--

--

Puneet Grover

Android Team Lead (Senior Consultant) @Deloitte USI | Google Certified Android Dev | Java | Kotlin | Blogger | Sometimes Youtuber