Kotlin

run — Compute With Scope

admin by @admin ADMIN
Jun 14, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`x.run { ... }` is `apply` but returns the block's LAST expression instead of `x`. Top-level `run { ... }` (no receiver) is useful for inline computation blocks.
Kotlin
Raw
data class User(val name: String, val email: String, val age: Int)

fun main() {
    val user = User("Alice", "a@x.com", 30)

    // run with a receiver — compute a transformed value
    val summary: String = user.run {
        "$name <$email> ($age yrs)"        // implicit `this.`
    }
    println(summary)

    // run without a receiver — encapsulate temporary state
    val factor = run {
        val configured = System.getenv("SCALE_FACTOR")?.toIntOrNull()
        configured ?: 1
    }
    println(factor)

    // run for early return value computation
    fun greet(name: String?): String = name?.run {
        "Welcome back, $this!"           // `this` is the non-null name
    } ?: "Welcome, guest"

    println(greet("Alice"))
    println(greet(null))
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.