CodeGym /Courses /Kotlin SELF /Smart cast after null checks

Smart cast after null checks

Kotlin SELF
Level 11, Lesson 4
Available

1. Basic smart cast cases

When you’re just starting to write code, it may seem like the compiler is a nasty teacher: “you can’t call .length because it’s a String?.” But in reality the compiler can be very friendly: if you prove to it that the value is not null, it will temporarily treat the variable as non-null and let you write normal code without ?..

This is called smart cast—an automatic “type narrowing” inside a safe scope. In Kotlin 2.x (the K2 compiler) there are more such situations, and the analysis is smarter, but the principle is still the same: the compiler starts “trusting” a variable only where the guarantee cannot suddenly disappear.

Imagine that String? is a box that might contain a string, or might contain emptiness. Smart cast is the moment when you look into the box, see a string, and say: “OK, as long as I haven’t blinked and nobody has touched the box, we’ll assume the string is definitely there.”

After if (x != null)

The nicest scenario: you checked a variable for null, and inside the if branch the compiler allows you to treat it like a normal, non-null variable. At that point the code becomes much cleaner: instead of chains of ?. you write ordinary method and property accesses.

That’s exactly why people love smart cast: it makes code safe, readable, and free of extra “punctuation.” It also helps you think in terms of program logic: “in this branch, the value definitely exists.”

Example: function parameter (the most reliable case)

fun printNicknameInfo(nickname: String?) {
    if (nickname != null) {
        println("Nickname length: ${nickname.length}")  // Nickname length: 3 (for example)
        println("Uppercase: ${nickname.uppercase()}") // Uppercase: NEO
    }
}

Why does this usually work perfectly? Because the parameter nickname inside the function doesn’t “jump around” by itself: you don’t reassign it. The compiler sees the check nickname != null and assumes that inside the if block it can be treated as a String.

Example: guard clause (early exit)—smart cast without nesting

fun formatNickname(nickname: String?): String {
    if (nickname == null) return "(anonymous)"
    return nickname.uppercase()
}

After the return, only the branch where nickname is definitely not null remains, and the compiler understands that. This style is often easier to read than a large if/else, because the code goes “straight” instead of wandering through a branching maze.

Smart cast and &&

You’ve already seen how && lets you write shorter code: if the left side is false, the right side is not evaluated. For null-safety this is a real gift: the expression x != null && x.length > 3 is safe because x.length will only be evaluated when x is not null.

And the compiler takes this into account: in the second part of the condition, x is often smart-cast to non-null. So && works like a mini-document: “first check that it exists, then use it.”

Example: null check + length check

fun isGoodNickname(nickname: String?): Boolean {
    return nickname != null && nickname.length >= 3
}

fun main() {
    println(isGoodNickname(null))     // false
    println(isGoodNickname("ab"))     // false
    println(isGoodNickname("neo"))    // true
}

Here nickname.length does not require ?. because the right side runs only when nickname != null.

Example: “empty string” vs null

fun main() {
    val raw = "   "
    val nickname: String? = raw.trim().ifEmpty { null }

    if (nickname != null && nickname.isNotBlank()) {
        println("Nickname: ${nickname.uppercase()}")
    } else {
        println("Nickname not set") // Nickname not set
    }
}

Note the idea: null means “no value,” while " " means “there is a value, but it’s junk.” That’s why sometimes you normalize the string first and only then rely on smart cast.

3. Sometimes smart cast doesn’t work

This is where the classic beginner complaint appears: “But I checked it! Why doesn’t the compiler believe me?!”

Answer: the compiler trusts you only when the variable is stable, meaning it cannot be changed between the check and the use. The most common enemy is var. You can change a var yourself in the code, and sometimes the variable can change through a function call or a closure (yes, the moment when a variable “lives” in an outer scope and someone inside a function touches it).

From the compiler’s point of view the logic is: “You checked nickname != null. But if it’s a var, who guarantees that one line later it didn’t become null?” And the compiler, like a cautious person, prefers to play it safe.

Example: a var can be changed right inside if

fun main() {
    var nickname: String? = "neo"

    if (nickname != null) {
        nickname = null

        println(nickname.length) // you can't write this: after reassignment nickname can be null again
        println(nickname) // null
    }
}

Here it’s obvious even to a human that nickname.length after nickname = null is a bad idea. The compiler simply won’t let you do something silly.

Example: a function changes the variable

fun main() {
    var nickname: String? = "neo"

    fun dropNickname() {
        nickname = null
    }

    if (nickname != null) {
        dropNickname()

        println(nickname.length) // the compiler won't allow it: nickname could have become null
        println(nickname?.length)   // null
    }
}

For the compiler, dropNickname() is a “black box.” Even if you currently know what the function does, tomorrow you (or a teammate) may add logic there, and the guarantee will disappear. Kotlin prefers safety.

Example: “checked one thing, using another” (a subtle logical trap)

fun main() {
    var nickname: String? = "neo"

    val ok = nickname != null
    if (ok) {
        // Inside the block, nickname is not automatically String,
        // because we checked ok, not nickname directly.
        println(nickname?.length) // 3
    }
}

In Kotlin 2.x the compiler has become better at discovering such proofs from code in some cases, but as a rule of thumb for beginners it’s better to think like this: smart cast works most reliably when the check is right next to the usage.

4. What to do if smart cast didn’t work

When smart cast doesn’t work, it’s very easy to “rage” and slap in a !!. That’s like covering the warning light on a dashboard with tape: the problem disappears visually, but the car can still start smoking sadly.

Much better is to have three sane strategies: take a snapshot into a val, use ?./?:, or restructure the code so the check is closer to the usage.

Strategy A: snapshot—store the value in a val

fun main() {
    var nickname: String? = "neo"

    val snapshot: String? = nickname
    if (snapshot != null) {
        println(snapshot.length) // 3
    }
}

Why does this work? Because snapshot is a val. It can’t be reassigned, so within the if block the compiler considers it stable and happily smart-casts it.

Strategy B: safe call ?. + Elvis ?:

fun main() {
    val nickname: String? = null

    val len: Int = nickname?.length ?: 0
    println("Nickname length: $len") // Nickname length: 0
}

This is a good style when you need a “one-liner” computation: if the value exists, take the length; if not, use a default.

Strategy C: restructure using an early return

fun printUpper(nickname: String?) {
    if (nickname == null) {
        println("Nickname not set")
        return
    }

    println(nickname.uppercase())
}

fun main() {
    printUpper(null)    // Nickname not set
    printUpper("neo")   // NEO
}

Here you don’t force the compiler to be telepathic: you explicitly separate the null branch, and then work with non-null afterward.

5. How the compiler thinks: a diagram and a table

Sometimes it helps to imagine that the compiler is a very picky bouncer at the entrance to the “.length()” club. It lets in only those who can prove “I’m not null,” and only if nobody can swap the ID on the way.

This is not an exact internal model of the compiler, but as a “mental picture” it’s useful.

flowchart TD
    A["There is a variable x: T?"] --> B{"Did we check x != null?"}
    B -- "no" --> C["Need ?. / ?: / if / return"]
    B -- "yes" --> D{"Is x stable?"}
    D -- "yes (val / parameter / local snapshot)" --> E["Smart cast: x is treated as T inside the scope"]
    D -- "no (var may change)" --> F["Compiler disallows x.member without safe access"]

And one more small table to reinforce the idea of “stability” without diving into compiler magic:

What we check for null Does smart cast usually work? Why
Function parameter p: String? Yes A parameter can’t be reassigned; it’s stable within the function body
Local val x: String? Yes val does not change
Local var x: String? Sometimes As long as the compiler is sure that x won’t change before it’s used
A var that a function/closure may change Often no The compiler can’t guarantee that x won’t become null

6. Mini-app: user questionnaire

Let’s build a small console app that asks the user for a nickname (can be skipped) and then prints a greeting. We’ll intentionally write the code so we encounter both a “pleasant” smart cast, and a situation where it doesn’t work, and a snapshot-based fix.

The idea is simple: the user enters a string. If after trim() it’s empty, we consider the nickname not set, i.e. null. This is exactly the case where null makes sense: “the user didn’t provide a value.”

Version 1: linear code with classic smart cast

fun main() {
    print("Enter nickname (Enter to skip): ")
    val raw = readln().trim()

    val nickname: String? = if (raw.isEmpty()) null else raw

    if (nickname != null) {
        println("Hi, ${nickname.uppercase()}!") // Hi, NEO! (for example)
    } else {
        println("Hi, stranger!")              // Hi, stranger!
    }
}

Here nickname is a val, so inside if (nickname != null) the compiler calmly treats nickname as a String.

Version 2: add a var and a “suspicious” function

Now imagine we want to allow “resetting the nickname” by some logic (for example, by a special command). This is an artificial example, but it perfectly shows the reason smart cast is rejected.

fun main() {
    print("Enter nickname (Enter to skip): ")
    val raw = readln().trim()

    var nickname: String? = if (raw.isEmpty()) null else raw

    fun maybeDropNickname() {
        // Imagine there is complex logic here.
        // For the example, "complex logic" is just a reset.
        nickname = null
    }

    if (nickname != null) {
        maybeDropNickname()

        // println(nickname.length) // the compiler won't allow it
        println("Nickname length: ${nickname?.length}")  // Nickname length: null
    }
}

The key point is the very fact: since nickname is a var and there is a function that can change it, the compiler won’t let you treat it like a String after the check.

Version 3: fix it with a snapshot (and keep readability)

fun main() {
    print("Enter nickname (Enter to skip): ")
    val raw = readln().trim()

    var nickname: String? = if (raw.isEmpty()) null else raw

    fun maybeDropNickname() {
        nickname = null
    }

    val snapshot = nickname
    if (snapshot != null) {
        // Even if nickname changes later, snapshot won't change anymore
        println("Hi, ${snapshot.uppercase()}!") // Hi, NEO!
    }

    maybeDropNickname()
    println("nickname right now: $nickname")           // nickname right now: null
}

Meaning: if you need to “freeze the value at the moment of the check,” take a snapshot. This is a very common technique in real code, even before you move on to more complex programs.

7. Common mistakes when using smart cast with null

Mistake No. 1: thinking that the check x != null makes x safe “forever.”
Smart cast applies in a specific scope, usually inside an if block, and only while the compiler is sure the value cannot change. Once you leave the block or change the variable, the guarantee is gone—and that’s normal: the code should honestly reflect where you have proof and where you no longer do.

Mistake No. 2: “fixing compilation” with !! because “I know for sure.”
!! is not “please make it compile,” it’s “if this is null, crash the program.” Sometimes that behavior is truly needed, but in most learning tasks it’s just a way to hide a bug. Usually it’s better to use if, ?., ?:, or a snapshot into a val, and make the null scenario explicit.

Mistake No. 3: separating the check and the usage too far apart.
When there are ten lines, function calls, or nested conditions between if (x != null) and the usage of x, it’s harder for the compiler to guarantee safety, and harder for a human to read the code. A good style is either to use the value immediately inside the branch, or store a snapshot in a val, or do an early return so the code stays linear.

Mistake No. 4: trying to “convince” the compiler instead of helping it with code structure.
Beginners sometimes start rearranging braces, adding extra checks, or writing “magic” constructs, hoping smart cast will suddenly appear. Usually it’s better not to guess, but to choose a simple strategy: snapshot, ?./?:, early return. Kotlin values clear code and willingly plays along with it.

1
Task
Kotlin SELF, level 11, lesson 4
Locked
Profile nickname
Profile nickname
1
Task
Kotlin SELF, level 11, lesson 4
Locked
Bot greeting
Bot greeting
1
Task
Kotlin SELF, level 11, lesson 4
Locked
Password validation
Password validation
1
Task
Kotlin SELF, level 11, lesson 4
Locked
Comment snapshot
Comment snapshot
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION