run and with

run

run is like let but the object is this, so you can call its members directly. Without a receiver, run { } just groups statements into an expression.

Example

class Invoice(val items: List<Int>, val gstRate: Double)

fun main() {
    val invoice = Invoice(listOf(500, 300, 200), 0.18)
    val total = invoice.run {
        val subtotal = items.sum()
        subtotal + subtotal * gstRate
    }
    println("Total: $total")

    val greeting = run {
        val hour = 9
        if (hour < 12) "Good morning" else "Good evening"
    }
    println(greeting)
}

Output

Total: 1180.0
Good morning

with

Example

with(obj) { } takes the object as an argument. Read it as "with this object, do the following".

fun main() {
    val sb = StringBuilder()
    val text = with(sb) {
        append("Order #1021")
        append(" | ")
        append("3 items")
        toString()
    }
    println(text)

    val config = mapOf("host" to "api.shop.in", "port" to "443")
    with(config) {
        println("https://${get("host")}:${get("port")}")
    }
}

Output

Order #1021 | 3 items
https://api.shop.in:443