Careeroza
let
Null Checks with ?.let
?.let { } runs the block only when the value is not null. Inside, it is a non-null type. Combine with ?: for the null case.
Example
fun sendOtp(phone: String?) {
phone?.let { println("OTP sent to ${it.takeLast(4).padStart(10, '*')}") }
?: println("No phone number on file")
}
fun main() {
sendOtp("9876543210")
sendOtp(null)
val length = "Kotlin".let { word ->
println("Measuring $word")
word.length
}
println(length)
}Output
OTP sent to ******3210 No phone number on file Measuring Kotlin 6