CodeBlanks Logo Icon CodeBlanks

Null check

Learn null checking with if (x != null).

Null check: if (x != null)

When you check a nullable variable with if (x != null), the compiler smart-casts x to its non-null type inside the block. You do not need !!.

val name: String? = "Ava"
if (name != null) {
    println(name.length)  // smart cast: String
}

Outside the block name is still String?; the null-risk remains. This keeps the check valid only inside the block.

Null check and early return

The if (x == null) return pattern handles the null case early at the top of a function, so the rest of the code can be written as non-null. This avoids needless nesting.

fun greet(name: String?) {
    if (name == null) return
    println("Hello $name")
}

After the early return, name is now String; no ?. or !! is needed. This technique is especially useful when validating at the top of a function.

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 Outside the if (name != null) block, what is the type of name?

  • String (smart cast)
  • Any
  • Unit
  • String? Correct answer

Explanation: Outside the block name is still String?; smart cast applies only inside.

2 Match expression to role

Term Meaning
if (x != null) Inside, x is non-null
if (x == null) Inside, x is null
smart cast Type narrows automatically
return Early exit from block

3 Fill in the blank: null check

Question
if (name ____ null) { println(name.length) }
Answer
if (name != null) { println(name.length) }

Explanation: Inside the if (name != null) block, name is non-null.

All lessons in Beginner