Safe Call Operator

Using ?.

Example

a?.b means: if a is not null, call b; otherwise the whole expression is null. No crash.

fun main() {
    val couponCode: String? = "SAVE50"
    val noCoupon: String? = null

    println(couponCode?.length)
    println(noCoupon?.length)
    println(noCoupon?.uppercase())
}

Output

6
null
null

Chaining Safe Calls

Example

Safe calls can be chained. If any part is null, the result is null.

fun main() {
    val apiCity: String? = "  mumbai "
    val missing: String? = null

    println(apiCity?.trim()?.uppercase())
    println(missing?.trim()?.uppercase())
}

Output

MUMBAI
null

Tip: In Java the same chain needs a nested if (a != null && a.b() != null ...).