CodeBlanks Logo Icon CodeBlanks

Summary - Null safety

Combine ?, !!, ?: and let to write a null-safe function.

Summary: ?, !!, ?: and let together

In this summary you will combine the null-safe tools. A nullable value can be processed with ?.let and given a fallback with ?:. !! is used only at points where you say "I am sure".

val name: String? = null
name?.let { println("Hello $it") } ?: println("Guest")
// Guest

This chain prints "Guest" when null; otherwise it greets. So one line manages both branches.

Practice Greet with let and Elvis together

Define a val name: String? = null. Print a null-safe greeting with name?.let { println("Hello $it") } ?: println("Guest").

Starter code

Main.kt
fun main() {
    val name: String? = null
    // If name is null print "Guest", else print "Hello $it" (use let ?:)
}

Sample solution

Main.kt
fun main() {
    val name: String? = null
    name?.let { println("Hello $it") } ?: println("Guest")
}

Expected output

Guest

Practice Print length with if (name != null)

Define a val name: String? = "Ava". Inside an if (name != null) block, print the length with println(name.length).

Starter code

Main.kt
fun main() {
    val name: String? = "Ava"
    // If name is not null, print its length (use if != null)
}

Sample solution

Main.kt
fun main() {
    val name: String? = "Ava"
    if (name != null) {
        println(name.length)
    }
}

Expected output

3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which uses let and Elvis together?

  • if (name == null) println(name)
  • name?.let { println(it) } ?: println("Guest") Correct answer
  • name!! + name?.length
  • println(name)

Explanation: ?.let runs when not null, ?: gives a default when null.

2 Match operator to role

Term Meaning
?. Safe call
!! Non-null assertion
?: Elvis default
?.let { } Null-safe block

All lessons in Beginner