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
- Nullable Types and the ? Modifier
- Safe Call ?. and Elvis ?: in Real Code
- let, also, and run with Nullable Receivers
- !! Operator: When and Why to Avoid It