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.
✅ 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.
3. with
👉 Context object: this
👉 Return value: Lambda result
Used to operate on an object without changing it.
⚠
withis not an extension function.
4. apply
👉 Context object: this
👉 Return value: Context object
Used for object configuration / initialization.
5. also
👉 Context object: it
👉 Return value: Context object
Used for additional actions like logging or debugging.
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
