How to Use run Function in Kotlin: Simple Guide
In Kotlin, the
run function executes a block of code and returns its result. It is useful for scoping variables or running code expressions in a concise way.Syntax
The run function takes a lambda block and executes it, returning the last expression's value inside the block.
Syntax parts:
run { ... }: Runs the code inside the curly braces.- The block can contain multiple statements.
- The result of the block is returned by
run.
kotlin
val result = run {
val x = 10
val y = 20
x + y // last expression returned
}Example
This example shows how run executes a block and returns the sum of two numbers. It also demonstrates scoping variables inside run.
kotlin
fun main() {
val sum = run {
val a = 5
val b = 7
a + b
}
println("Sum is $sum")
}Output
Sum is 12
Common Pitfalls
Common mistakes when using run include:
- Not returning a value explicitly if the last expression is missing.
- Using
rununnecessarily when simple expressions suffice. - Confusing
runwith other scope functions likeletorapply.
Example of a pitfall and fix:
kotlin
// Wrong: no value returned explicitly, returns Unit val result = run { val x = 10 val y = 20 println(x + y) // prints but returns Unit } // Right: last expression is returned val correctResult = run { val x = 10 val y = 20 x + y }
Quick Reference
| Feature | Description |
|---|---|
| Purpose | Execute a block and return its result |
| Return value | Last expression inside the block |
| Scope | Variables inside block are local |
| Common use | Scoping, initialization, chaining expressions |
Key Takeaways
The run function executes a block and returns the last expression's value.
Use run to limit variable scope and write concise code blocks.
Always ensure the last expression in run returns the desired value.
Avoid using run when a simple expression or other scope functions fit better.
run is useful for initialization and chaining expressions cleanly.