Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. run / with

run / with

Scope functions that execute a code block within the context of an object and return the result. run is called as an extension function on the object, while with is a regular function that takes the object as an argument.

Syntax

// run: called as an extension function. References the object as this inside the lambda.
object.run {
    // You can access properties and methods without this.
    returnValue
}

// with: called as a regular function. The object is passed as an argument.
with(object) {
    // You can access properties and methods without this.
    returnValue
}

Overview

FunctionContext referenceReturn valueCommon use
run { }this (optional)Lambda resultConfigure an object and return a result.
with(obj) { }this (optional)Lambda resultPerform multiple operations on a non-null object.

Sample Code

data class User(var name: String, var age: Int, var email: String)

fun main() {
    // run: compute a value using the object's properties.
    val user = User("Taro", 25, "taro@example.com")
    val summary = user.run {
        // this = user. You can omit this.
        "Name: $name, Age: $age"
    }
    println(summary) // Name: Taro, Age: 25

    // run: combine a null check with further processing.
    val nullableUser: User? = user
    val result = nullableUser?.run {
        "Email: $email"
    }
    println(result) // Email: taro@example.com

    // with: group multiple property accesses together.
    val report = with(user) {
        buildString {
            appendLine("=== User Info ===")
            appendLine("Name: $name")
            appendLine("Age: $age")
            append("Email: $email")
        }
    }
    println(report)

    // with: use the object while accessing its members.
    val numbers = mutableListOf(3, 1, 4, 1, 5, 9)
    val max = with(numbers) {
        sort()
        last() // The last expression in the lambda is the return value.
    }
    println("Max: $max") // Max: 9
}

Overview (Details)

Both run and with reference the object as this (which can be omitted) inside the lambda, and return the last expression of the lambda as the result. The main difference is how they are called: run is an extension function written as object.run { }, while with is a regular function written as with(object) { }.

Because with cannot be combined with the safe-call operator (?.), use run when the object could be null. If you only need to call multiple methods and do not need a return value, consider apply, whose return value is the receiver itself.

If you find any errors or copyright issues, please .