Skip to content
Scope Functions: let, run, with, apply, also
step 1/6

Reading — step 1 of 6

Learn

~1 min readIdiomatic Kotlin

Kotlin provides 5 scope functions that take a receiver and a lambda. They differ in (a) what this refers to, and (b) what the function returns.

FunctionReceiver nameReturns
let { it -> }itlast expr
run { this -> }thislast expr
with(x) { this -> }thislast expr
apply { this -> }thisthe receiver
also { it -> }itthe receiver

let — usually for null checks + transformations:

val len: Int? = name?.let { it.length }    // null-safe transform

apply — configure an object then return it:

val user = User().apply {
    name = "Ada"
    email = "[email protected]"
}

also — side effects, return the original:

val user = createUser().also { logger.info("created $it") }

run — like apply but returns the lambda result:

val result = transaction.run {
    debit(100)
    credit(50)
    commit()             // last expr — returns whatever commit() returns
}

with — like run but takes the object as a parameter (different syntax):

val summary = with(user) {
    "$name ($email): $age"
}

Mnemonic: apply/also return the receiver (chainable). let/run/with return the lambda result.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…