Kotlin

Cheatsheet: let / apply / also / run / with

admin by @admin ADMIN
2d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
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
Raw
// |   Function | Receiver | Returns      | Use for                         |
// |-----------|---------|--------------|----------------------------------|
// |   let     |  it     | block result | null-safe scope / transformations |
// |   run     |  this   | block result | compute from `this`               |
// |   apply   |  this   | object       | configure & return same object    |
// |   also    |  it     | object       | side effects (logging, asserts)   |
// |   with    |  this   | block result | non-extension form of run         |

fun main() {
    val s = "  Hello  "

    s.let    { it.trim() }                  // → "Hello"            (transform)
    s.run    { trim() }                     // → "Hello"            (use `this`)
    s.apply  { /* no mutation possible — String is immutable */ }   // → "  Hello  "  (configure & return)
    s.also   { println("about to use $it") }                         // → "  Hello  "  (side effect)
    with(s)  { trim() }                     // → "Hello"            (use as non-extension)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.