Using the 'let' Function for Null Safety and Scoping

The 'let' function in Kotlin is a powerful tool that allows you to execute a block of code only if the object is not null. This aids in handling nullable types gracefully and reduces the risk of null pointer exceptions. Additionally, it provides a scoped context for the object, making the code cleaner and easier to read.

val name: String? = "Kotlin"

name?.let { nonNullName ->
    println("The name is $nonNullName")
} ?: run {
    println("Name is null")
}