0Pricing
Kotlin Academy · Lesson

Safe Call ?. and Elvis ?: in Real Code

Chain safe calls and provide fallback values using the Elvis operator.

Two Operators, Big Impact

The safe call ?. calls a member only if the receiver is non-null. The Elvis operator ?: provides a fallback when the left side is null.

Safe Call Basics

x?.member evaluates to null if x is null; otherwise it accesses member normally.

fun main() {
    val name: String? = "Kotlin"
    val len: Int? = name?.length
    println(len) // 6
    val nope: String? = null
    println(nope?.length) // null
}

All lessons in this course

  1. Nullable Types and the ? Modifier
  2. Safe Call ?. and Elvis ?: in Real Code
  3. let, also, and run with Nullable Receivers
  4. !! Operator: When and Why to Avoid It
← Back to Kotlin Academy