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.
| Function | Receiver name | Returns |
|---|---|---|
let { it -> } | it | last expr |
run { this -> } | this | last expr |
with(x) { this -> } | this | last expr |
apply { this -> } | this | the receiver |
also { it -> } | it | the 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…