Kotlin

with — Scope an Existing Object

admin by @admin ADMIN
Jun 18, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`with(x) { ... }` is `run` flipped: the receiver is the first argument. Reads naturally when you're doing several things to an existing object without chaining.
Kotlin
Raw
data class Order(val id: Int, var status: String, var paidAt: Long?)

fun main() {
    val order = Order(42, "pending", null)

    // Multi-step mutation/access on the same object
    with(order) {
        status  = "paid"
        paidAt  = System.currentTimeMillis()
        println("Order $id is $status")
    }

    // with as expression: returns the last value
    val summary = with(order) {
        "Order $id paid at $paidAt"
    }
    println(summary)

    // Useful for chained API calls on Java objects
    val sb = StringBuilder()
    with(sb) {
        append("Hello, ")
        append("world!")
        append(" — ")
        append(42)
    }
    println(sb)
}
Tags

Save your own code snippets

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