Thuta Learning
BasicProgrammingbeginner

Safe Calls & Elvis Operator

Relax. We'll talk through this in plain words — no textbook voice.

When working with nullable values, you use the safe call operator ?. and the Elvis operator ?: to avoid crashes. Once you understand these two, you can handle API responses, optional user profile data, and database fields more safely.

kotlin
fun main() {
    val name: String? = null

    val length = name?.length
    println("Length: $length")

    val displayName = name ?: "Guest User"
    println("Welcome, $displayName")
}
You should see
Length: null Welcome, Guest User

Summary

Don't handle nullable values directly. Use ?. and ?: to build a safe path instead.

Easy traps

  • Using name!!.length when it's not really necessary can cause a crash if name turns out to be null.

Practical example — profile bio

Practical example — profile bio

kotlin
fun main() {
    val bio: String? = null
    val shortBio = bio?.take(20) ?: "No bio added yet"

    println(shortBio)
}

You'll know it worked when: No bio added yet

Safe Calls & Elvis Operator | Thuta Learning