0Pricing
Kotlin Academy · Lesson

let, also, and run with Nullable Receivers

Use scope functions to execute code only when a value is non-null.

Scope Functions Meet Nullables

Scope functions let, also, and run pair beautifully with the safe call ?. to execute a block only when the receiver is non-null.

let with Safe Call

obj?.let { ... } runs the block only if obj is non-null; inside, it refers to the non-null value.

fun main() {
    val name: String? = "Kotlin"
    name?.let {
        println("Length: ${it.length}")
        println("Upper: ${it.uppercase()}")
    }
}

All lessons in this course

  1. Nullable Types and the ? Modifier
  2. Safe Call ?. and Elvis ?: in Real Code
  3. let, also, and run with Nullable Receivers
  4. !! Operator: When and Why to Avoid It
← Back to Kotlin Academy