Author profile picture

with() (scope function)

Overview

The with() function is a scope function found in the Kotlin standard library. Unlike let(), also(), run() with receiver, and apply(), with() is not an extension function, but instead accepts the receiver as an argument.

Example

val size = with("Hello") {
    println(this)
    length
}

In this example, the string “Hello” is printed, and then its length is assigned to the size variable.

Characteristics

When the with() extension function executes:

  • the receiver passed as the first argument is available as this inside the code block
  • the result of with() will be the result of the code block passed to it

Use Cases

with() is functionally the same as the extension function version of run(), so it’s well-suited to the use case of Initialize and Execute.

Alternatives

Although with() and run() are almost identical, there are still a couple of trade-offs that you make when choosing one over the other. Check out the guide, Choosing between with() and run(), to understand the differences.

The other scope functions might also suit your needs. The guide, Understanding Kotlin’s let(), also(), run(), and apply(), explains them in detail.

Share this article: