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:. (Related: Few-shot learning in practice: GPT-Neo and the 🤗 Accele...)
“Why are there FIVE of them… and why do they all look the same?” 😅.
It has been revealed that 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. (Related: Industry News: Block Sparse Matrices for Smaller and Fa...)
Imagine you’re setting up a newly introduced User object. Without scope functions, you’d do this:.
According to recent reports, 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:.
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.
🔍 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.
👉 Here, it represents the object (name).
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.
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.
👉 Cleaner than repeating person.name, person.age.
It has been revealed that 4. apply — Object Configuration — Use this · Returns the object itself.
Sources indicate that 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.
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.
In a recent development, 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.
👉 It returns the original object unchanged.
Instead of memorizing everything, just remember this:.
A real-world example that uses all five.
According to recent reports, here’s a contrived-but-illustrative snippet that indicates 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.
Because each one solves a slightly different problem:.
In a recent development, 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.
According to recent reports, 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.
Sources indicate that 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.
Scope functions are one of those things you pick up gradually. At first, scope functions feel like overkill. But once you start using them:.
It has been revealed that 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..!!
