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
