Kotlin Scope Functions

Kotlin Scope Functions

Scope functions in Kotlin are used to execute a block of code within the context of an object. They make code cleaner, more readable, and concise.

The five scope functions are:

  • let

  • run

  • with

  • apply

  • also


1. let

👉 Context object: it

👉 Return value: Lambda result

Used mainly for null checks and local variable scoping.

val name: String? = "Kotlin"

name?.let {
println("Length = ${it.length}")
}

✅ Executes only if name is not null.


2. run

👉 Context object: this

👉 Return value: Lambda result

Used when you want to initialize an object and compute a result.

val result = "Kotlin".run {
length + 10
}
println(result)

3. with

👉 Context object: this

👉 Return value: Lambda result

Used to operate on an object without changing it.

val person = Person("Sanjit", 22)

val info = with(person) {
"Name: $name, Age: $age"
}

println(info)

with is not an extension function.


4. apply

👉 Context object: this

👉 Return value: Context object

Used for object configuration / initialization.

val person = Person("","").apply {
name = "Rahul"
age = 25
}

5. also

👉 Context object: it

👉 Return value: Context object

Used for additional actions like logging or debugging.

val list = mutableListOf(1, 2, 3)
.also {
println("Original list: $it")
}
.add(4)

Comparison Table

Function Context Returns Common Use
let it Result Null check
run this Result Compute value
with this Result Group operations
apply this Object Object setup
also it Object Side-effects

When to Use What?

  • let → when working with nullable objects

  • apply → when configuring objects

  • also → for logging or side actions

  • run / with → when you need a calculated result


Summary

  • Scope functions reduce boilerplate code

  • Improve readability

  • Each function has a specific purpose

  • Choosing the right one makes code cleaner

You may also like...