Null Safety Patterns
Safe Calls
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
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)
}
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
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
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
wordmay be text ornull.word?.isNotEmpty()calls the method only whenwordis present.- A present non-empty word makes
hasTexttrue. - A null word skips the call and reports no text.
|
wordvalue | 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