Kotlin

let — Transform or Null-Safe Scope

admin by @admin ADMIN
Jun 14, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`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
Raw
fun main() {
    val name: String? = "Alice"

    // Only print if non-null — replaces "if (name != null) { ... }"
    name?.let { println("hello ${it.uppercase()}") }

    // Transform inside a chain
    val len: Int? = name?.let { it.length * 10 }
    println(len)                                    // 50

    // Chain after a builder
    val result = "  Some Input  "
        .trim()
        .let { it.lowercase() }
        .let { if (it.isEmpty()) "default" else it }
    println(result)                                 // some input

    // Useful for limiting variable scope
    val cleanedUrl = run {
        val raw = "  https://example.com  ".trim()
        if (raw.startsWith("http")) raw else "https://$raw"
    }
    println(cleanedUrl)
}
Tags

Save your own code snippets

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