liveBook · Manning

With

As explained in Kotlin in Action, 2E

with is a Kotlin standard-library scope function that executes a block with an object as its receiver and returns the block result.

with is a Kotlin standard-library function for performing several operations on one object without repeating its name. It passes the object as the receiver of a lambda, so the lambda can call the receiver’s methods directly. section 5.4.1

Build an alphabet with StringBuilder

fun alphabet() = with(StringBuilder()) { for (letter in 'A'..'Z') { append(letter) } append("\nNow I know the alphabet!") toString() } Here, StringBuilder is the receiver. Inside the lambda, append and toString can be called without repeating stringBuilder or writing this. The final expression, toString(), becomes the result returned by with. section 5.4.1

Use the receiver explicitly when clarity requires it:

  • this.append(letter) identifies the receiver directly; append(letter) uses the same receiver implicitly. section 5.4.1
  • with is a library function rather than a special language statement, although trailing-lambda syntax makes it resemble one. section 5.4.1
  • A lambda with a receiver resembles an extension function because both provide direct access to a receiver’s members. section 5.4.1

How Kotlin in Action, 2E covers it

How deep it goes
Explains invocation syntax, receiver access, implicit this, return value, and the analogy with extension functions.
Examples
Builds the alphabet with StringBuilder, using explicit and implicit receiver calls.
What it assumes
Assumes basic Kotlin lambdas while introducing receiver lambdas and direct member access.
What you can do after
Apply with to group operations on an object and return the lambda’s final expression.
How it connects
Connects lambdas with receivers to extension functions, apply, also, and trailing-lambda syntax.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.