Use ?. to read a member only when a value is present.

safe-call The safe-call operator returns `null` instead of calling through a missing value.

Safe Calls

word
SafeCalls.kt
Replay: real traced execution (multi-file project)
fun main() {
    val word: String? = "river"
    val hasText = word?.isNotEmpty() == true
    val report = if (hasText) "has text" else "no text"

    println("word=${word ?: "none"}")
    println(report)
}
fun main() {
    val word: String? = null
    val hasText = word?.isNotEmpty() == true
    val report = if (hasText) "has text" else "no text"

    println("word=${word ?: "none"}")
    println(report)
}
fun main() {
    val word: String? = "tree"
    val hasText = word?.isNotEmpty() == true
    val report = if (hasText) "has text" else "no text"

    println("word=${word ?: "none"}")
    println(report)
}
  1. word ← river, hasText ← true, report ← has text

    1fun main() {2    val word→ river: String? = "river" //@word=null, "tree"3    val hasText→ true = wordriver?.isNotEmpty() == true4    val report→ has text = if (hasTexttrue) "has text" else "no text"56    println("word=${wordriver ?: "none"}")7    println(reporthas text)8}
    outputword=river
    has text
  1. word ← null, hasText ← false, report ← no text

    1fun main() {2    val word→ null: String? = null3    val hasText→ false = wordnull?.isNotEmpty() == true4    val report→ no text = if (hasTextfalse) "has text" else "no text"56    println("word=${wordnull ?: "none"}")7    println(reportno text)8}
    outputword=none
    no text
  1. word ← tree, hasText ← true, report ← has text

    1fun main() {2    val word→ tree: String? = "tree"3    val hasText→ true = wordtree?.isNotEmpty() == true4    val report→ has text = if (hasTexttrue) "has text" else "no text"56    println("word=${wordtree ?: "none"}")7    println(reporthas text)8}
    outputword=tree
    has text

Follow the Safe Call

  1. word may be text or null.
  2. word?.isNotEmpty() calls the method only when word is present.
  3. A present non-empty word makes hasText true.
  4. A null word skips the call and reports no text. | word value | Safe-call result | Report | | --- | --- | --- | | "river" | true | has text | | null | null | no text |

Exercise: SafeCalls.kt

Use a safe call to check whether a nullable word has text and print a clear report