Null Safety Patterns in Kotlin

From the Kotlin cheat sheet · Null Safety · verified Jul 2026

Null Safety Patterns

Advanced null handling patterns

kotlin
// Scoped functions for null handling
val str: String? = "Hello"

// let - execute block if not null
str?.let {
    println("Length: ${it.length}")
}

// also - side effects
str?.also {
    println("Processing: $it")
}?.uppercase()

// run - execute block with receiver
val result = str?.run {
    println("Running on $this")
    length * 2
}

// takeIf / takeUnless
val email = "user@example.com"
val validEmail = email.takeIf { it.contains("@") }
val invalidEmail = email.takeUnless { it.contains("@") }
💡 Scoped functions (let, run, also) handle nullables elegantly
⚡ takeIf/takeUnless return value or null based on predicate
📌 Delegates.notNull() for properties initialized after construction
🟢 Contracts tell compiler about null state after function calls

More Kotlin tasks

Back to the full Kotlin cheat sheet