#scope-functions Clear
Tags #php #kotlin #bash #go #sql #rust #typescript #html #java #python #files #utils #strings #http #concurrency #async #json #arrays #security #types #crypto #database #dates #format
Kotlin Cheatsheet: let / apply / also / run / with
Five scope functions cover ~95% of "do something with x" patterns. Pick by two axes: receiver (this vs it) and return value (object itself vs block result).
Kotlin also — Side Effect, Return Itself
`x.also { ... }` runs a side-effect block with `x` as `it` and returns `x` unchanged. Used for logging, debugging, or asserting mid-chain without breaking it.
Kotlin with — Scope an Existing Object
`with(x) { ... }` is `run` flipped: the receiver is the first argument. Reads naturally when you're doing several things to an existing object without chaining.
Kotlin run — Compute With Scope
`x.run { ... }` is `apply` but returns the block's LAST expression instead of `x`. Top-level `run { ... }` (no receiver) is useful for inline computation blocks.
Kotlin let — Transform or Null-Safe Scope
`x.let { it.foo }` runs the block with `x` as `it` and returns the block's last expression. Combined with `?.`, it's the canonical "do this only if non-null" pattern.
Kotlin apply — Configure Object, Return Itself
`x.apply { ... }` runs the block with `x` as `this` (so you call methods/set properties directly) and returns `x`. The canonical builder-style configuration.