Scope functions run a block against an object. Pick by two axes: this versus it, and whether the block returns the object (apply/also) or a result (let/run/with). Overusing them nests into unreadable chains, so name a function when the chain gets clever.
This Kotlin cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- let: Object is
it. Returns lambda result. Great with?.letfor null and transforms. - run: Object is
this. Returns result. Useful for computing from several properties. - with: Not an extension:
with(obj) { }. Object isthis. Returns result. - apply: Object is
this. Returns the object. Builders and View setup. - also: Object is
it. Returns the object. Logging/side effects in a chain. - takeIf:
x.takeIf { predicate }returns x or null — pairs with?.let. - takeUnless: Opposite predicate of
takeIf. - Style: One scope function per chain when possible. Name
itif the type is unclear.
Copy-paste examples
apply for setup, let for null, also for a side effect
If a reviewer cannot see what is returned, rewrite as a named function.
data class Request(var url: String = "", var retries: Int = 0)
fun buildRequest(path: String) = Request().apply {
url = "https://api.example.com$path"
retries = 3
}.also { req ->
println("GET ${req.url}")
}
fun host(url: String?): String? =
url?.takeIf { it.startsWith("https://") }?.let { u ->
u.removePrefix("https://").substringBefore('/')
}Common mistakes
- Nesting
letinsideapplyinsiderununtil nobody knows the return type. - Using
applywhen you needed a mapped value (let/run). thisshadowing in nestedapplyso you assigned the wrong receiver.- Scope-function chains as a substitute for a real domain function name.
FAQ
- let vs apply?
lettransforms and returns a new value (it).applyconfigures and returns the same object (this).
- also vs let? Both use
it.alsoreturns the original object;letreturns the block result.
- Is BLOGPH0 outdated? No, but extension
runis often clearer.withis nice when the object is already a local and you want several calls.
Related Kotlin cheat sheets
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds mobile app development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.