let with Nullable Values

?.let { }

Example

x?.let { ... } runs the block only when x is not null. Inside the block the value is called it and is non-null.

fun main() {
    val email: String? = "[email protected]"
    val phone: String? = null

    email?.let {
        println("Sending receipt to $it")
    }
    phone?.let {
        println("Sending SMS to $it")     // skipped
    }

    // name the parameter instead of using 'it'
    email?.let { address -> println("Domain: ${address.substringAfter("@")}") }
}

Output

Sending receipt to [email protected]
Domain: gmail.com

Helpful Nullable Functions

Example

The standard library has many helpers for nullable values.

fun main() {
    val bio: String? = null
    val note: String? = "   "
    println(bio.isNullOrEmpty())
    println(note.isNullOrBlank())
    println(bio.orEmpty() + "<end>")

    val pinCodes: List<String?> = listOf("500081", null, "110001", null)
    println(pinCodes.filterNotNull())
    println(listOfNotNull("a", null, "b"))
}

Output

true
true
<end>
[500081, 110001]
[a, b]

Operators Summary

OperatorNameMeaning
T?nullable typevalue may be null
a?.bsafe callcall b only if a is not null, else null
a ?: bElvisa if not null, else b
a!!not-null assertiona, or throw NPE if null
a?.let { }safe letrun the block only if a is not null