Use ?.let { ... }.
The safe-call operator ?. makes sure let is called only when the value is not null. Inside the let block, the value is available as a non-null value, usually named it.
val name: String? = "Kotlin"
name?.let {
println("Name is $it")
println("Length is ${it.length}")
}
If name is "Kotlin", the block runs.
If name is null, the block is skipped.
You can also give the value a clearer name:
val name: String? = "Kotlin"
name?.let { nonNullName ->
println("Name is $nonNullName")
println("Length is ${nonNullName.length}")
}
To handle the null case too, combine it with the Elvis operator ?::
val name: String? = null
name?.let {
println("Name is $it")
} ?: println("Name was null")
So the general pattern is:
nullableValue?.let { value ->
// Runs only when nullableValue is not null
}
