Kotlin Scope Functions Tutorial: let, run, apply, also, and with Explained
This Kotlin Scope Functions tutorial explains the five main scope functions: let, run, apply, also, and with. Each function is explained with practical examples and best practices to help developers write clean, readable, and concise Kotlin code by scoping operations to an object. Scope functions are especially useful for null-safety, object configuration, and functional programming.
Kotlin Scope Functions – Complete Tutorial
Scope Functions Overview
Scope functions allow executing a block of code within the context of an object. They differ in:
- Return value – whether they return the object (
this) or the lambda result. - Context object – whether
thisoritis used inside the lambda.
The five main scope functions are: let, run, apply, also, and with.
1. let
- Executes code only if the object is not null.
itrefers to the object.- Returns the lambda result.
Example
Best Practices
- Use
letfor null checks and short transformations. - Chain multiple
letcalls for functional-style operations.
2. run
- Executes code in the context of
this. - Returns the lambda result.
Example
Best Practices
- Use
runwhen you want to compute a value using an object. - Good for initializing objects and returning a computation.
3. apply
- Executes code in the context of
this. - Returns the object itself.
- Commonly used for object initialization.
Example
Best Practices
- Use
applyfor configuring objects fluently. - Avoid returning values; focus on object setup.
4. also
itrefers to the object.- Returns the object itself.
- Useful for side-effects like logging.
Example
Best Practices
- Use
alsofor performing operations without affecting the chain of calls. - Ideal for logging or validation steps.
5. with
thisrefers to the object.- Returns the lambda result.
- Not an extension function; requires passing the object as a parameter.
Example
Best Practices
- Use
withwhen operating on an object multiple times without chaining. - Improves readability by avoiding repeated object references.
Summary
This chapter explained Kotlin’s scope functions: let, run, apply, also, and with. Scope functions help reduce boilerplate code, improve readability, and make operations on objects concise and expressive. Proper use enhances null safety, object configuration, and functional programming patterns.