DEV Community

Cover image for Kotlin Scope Functions Finally Explained (Without the Confusion)
supriya shah
supriya shah

Posted on

Kotlin Scope Functions Finally Explained (Without the Confusion)

Originally published on Medium:
https://medium.com/@supsabhi/kotlin-scope-functions-finally-explained-without-the-confusion-0cb943d6ced2?sharedUserId=supsabhi

Master these once, and suddenly every Kotlin codebase starts making a lot more sense.

If you’ve been learning Kotlin, chances are you’ve come across scope functions and thought:

“Why are there FIVE of them… and why do they all look the same?” 😅

When I first encountered Kotlin’s scope functions, my reaction was something similar.So don’t worry, you’re not alone.Scope functions are one of those Kotlin features that looks confusing on the surface but becomes genuinely delightful once it clicks. This article is that click..!

In this article, I’ll break down **SCOPE FUNCTIONS **in the simplest way possible — no jargon, just intuition and examples.By the end, you’ll know exactly what each one does, when to reach for it, and — just as importantly — when not to.

So, what even is a scope function?

A scope function is a function that executes a block of code within the context of an object. That’s the official definition, and it’s honestly not very helpful on its own.Let me try again.

Imagine you’re setting up a new User object. Without scope functions, you’d do this:

val user = User()
user.name = "Alice"
user.age = 30
user.email = "alice@example.com"
saveUser(user)
Enter fullscreen mode Exit fullscreen mode

That works fine. But notice how you keep writing user. over and over?

Scope functions let you “enter” the object for a moment, do everything you need, and step back out — without repeating yourself:

val user = User().apply {
name = "Alice"
age = 30
email = "alice@example.com"
}
saveUser(user)
Enter fullscreen mode Exit fullscreen mode

Cleaner, right? That’s the essence of it.

Basically all scope functions do the same thing:

👉 They run a block of code using an object

The real differences are:

  1. How they refer to the object (this vs it)
  2. What they return (object vs result)

🔍 Let’s Understand Them One by One

1.let — Safe Calls & Transformations. — Use it · Returns the lambda result

let takes the object as it inside the block, and returns whatever the last expression in the block evaluates to.

Use let when:

  • You want to work with a nullable object
  • You want to transform data

val cityName: String? = "Dubai"
cityName?.let {
println("Hello $it") it' is the non-null name
}
Enter fullscreen mode Exit fullscreen mode

👉 Here, it represents the object (name)

💡 Common use case:

  • Avoid null checks
  • Perform small transformations

2.run — Initialize + Compute Result — Use this · Returns the lambda result

run is like let, but instead of it, the object becomes this inside the block — so you can access its members directly without a prefix.

Use run when:

  • You want to execute multiple operations
  • You want to return a result
val result = user.run {
// 'this' is the user object
"${name} is ${age} years old"
}
Enter fullscreen mode Exit fullscreen mode

3. with — Operate on an Object (Non-extension)-Use this · Returns the lambda result · Not an extension

with is the odd one out — you pass the object as an argument rather than calling it on the object. Everything else is similar to run.

Use with when:

  • You already have an object
  • You want cleaner code
val person = Person("John", 25)
with(person) {
println(name)
println(age)
}
Enter fullscreen mode Exit fullscreen mode

👉 Cleaner than repeating person.name, person.age

4. apply — Object Configuration — Use this · Returns the object itself

This is the builder’s best friend. apply gives you this inside the block, and when you’re done, it returns the original object — not the result of the block.

Use apply when:

  • You want to configure an object
  • You want the same object back

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

This is perfect for configuring an object right after creating it. The classic use case for object initialization.

5.also — Side Effects (Logging, Debugging) — Use it · Returns the object itself

also is like apply, but uses it instead of this. It’s great when you want to do something extra with the object — like log it — without interrupting the main flow.

Use also when:

  • You want to do something extra (like logging)
  • Without modifying the object
val number = 10.also {
println("Value is $it")
}
Enter fullscreen mode Exit fullscreen mode

👉 It returns the original object unchanged

Simple Trick to Remember

Instead of memorizing everything, just remember this:

  • Need result? → let, run, with
  • Need object back? → apply, also
  • Using it? → let, also
  • Using this? → run, with, apply

A real-world example that uses all five

Here’s a contrived-but-illustrative snippet that shows them all working together. Don’t use all five in one chain like this in real code — but it’s a great way to see the differences side by side.

fetchUser()
?.let { rawUser -> // null-check, rename to rawUser
validateUser(rawUser) // returns a validated User
}
?.apply { // configure the validated user
role = "admin"
verified = true
}
?.also { // side effect: log it
println("Saving: ${it.name}")
}
?.run { // compute a result
saveUser(this) // returns the save result
}
Enter fullscreen mode Exit fullscreen mode

Why So Many Scope Functions?

Because each one solves a slightly different problem:

  • Cleaner null handling → let
  • Computation → run
  • Object setup → apply
  • Side effects → also
  • Readability → with

Common beginner mistakes

Using apply when you need a result. If you find yourself ending an apply block with a value you want to capture, switch to run. apply always gives you back the object, ignoring your last expression.

Chaining scope functions for no reason. Scope functions make code more readable — but only when used purposefully. If a plain if statement is clearer, use it. Readability wins.

Forgetting that with isn’t null-safe. You can’t do nullableObj?.with { … } because with isn’t an extension function. Reach for let or run when null safety is involved.

Final Thoughts

Scope functions are one of those things you pick up gradually. At first, scope functions feel like overkill. But once you start using them:

  • Your code becomes cleaner
  • You reduce repetition
  • You write more expressive Kotlin

Don’t try to memorize them — instead, start using just let and apply, which cover 80% of cases. The others will start feeling natural as you read more Kotlin code.
The next time you see let, run, or apply… don’t panic — you’re just one scope away from cleaner Kotlin 😄.. Happy Scoping..!!

Happy Coding ! 🚀 😄

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

This is the clearest version of this I've seen — the two questions at the end do most of the work for me: do I need the result back, or the object back, and am I dealing with it or this? I reach for let and apply most of the time too, and with is the one I keep forgetting, mostly because it isn't an extension function and isn't null-safe like the others. The warning about not chaining them just for the sake of it is a good one as well.