CodeGym /Courses /Kotlin SELF /Smart cast and how to use it

Smart cast and how to use it

Kotlin SELF
Level 41, Lesson 2
Available

1. Smart cast as a compiler promise

Smart cast is not magic and not mind reading. It is a very pragmatic compiler decision: if it is sure that at some point in the code a value has a narrower type (for example, String instead of String?), then it allows you to use it as that narrow type without an explicit as and without !!.

The key word is: sure. If there is even a small chance that the value changes between the check and the use, the compiler switches into “I don’t believe you, because later you’ll blame me” mode.

Let’s start with a situation where smart cast works perfectly, and it looks like “well, of course it should”:

fun printNameLength(name: String?) {
    if (name != null) {
        println(name.length) // ok: inside the block, name is treated as String
    }
}

Here name is a function parameter (essentially a local reference), and within the if block the compiler can guarantee: if we got here, then name is not null.

2. Why smart cast sometimes does not work

If you describe the problem in one phrase, it is this: smart cast works only where the compiler is sure the object is stable (will not change behind its back).

Kotlin is “suspicious” of several situations: mutable variables (var), object properties (obj.prop), especially if they can have a custom getter, and cases where a value is used inside a lambda and can be changed somewhere else.

Sometimes it feels unfair: with your eyes you see that “nothing changes”, but the compiler cannot prove it. The logic is simple: the compiler does not read your mind; it reads code and models risks.

var and “what if someone changes it?”

var is a favorite source of pain, because it literally means: “this can be changed”. And if the compiler sees that a variable in principle can change, it often refuses to smart-cast it across a longer region of code.

Let’s look at a realistic example: suppose in a CLI app we have a “current input line” (not the best design, but it happens in learning projects).

var currentLine: String? = null

fun printCurrentLineLength() {
    if (currentLine != null) {
        // The compiler may complain: currentLine is var, it can become null
        println(currentLine.length)
    }
}

Why can Kotlin complain? Because currentLine is read twice: once in the condition, and once in println. Between these reads, in theory any code could run (in a large project — an event handler, another function that changed global state, etc.). Even if right now you have “no threads” and “nothing like that”, the compiler still enforces the language contract, not the current mood of the project.

The classic fix is: take a snapshot into a local val.

var currentLine: String? = null

fun printCurrentLineLength() {
    val snapshot = currentLine
    if (snapshot != null) {
        println(snapshot.length) // ok: snapshot is val, stable in this block
    }
}

And this is an important habit: when in doubt, do one “controlled” read of a nullable value and then work only with a local val. It simplifies the code both for the compiler and for “future you in two weeks”.

obj.property is an accessor call, not a “variable”

A very common trap: we checked user.name != null, and then we want to use user.name.length. It seems logical, but the compiler looks at it differently.

The key idea: user.name is a property, and property access is not required to be “just a field read”. It can be a getter call (including a custom one), which can return a different value each time. Therefore the compiler often does not smart-cast user.name “for long”.

Minimal example:

class User(var name: String?)

fun printUserNameLength(user: User) {
    if (user.name != null) {
        // Often an error: smart cast is not applied to user.name
        println(user.name.length)
    }
}

Even if name is a regular var, the logic is the same: we read user.name twice. Between reads it can change (for example, someone assigned user.name = null).

The correct technique is, again, a snapshot:

class User(var name: String?)

fun printUserNameLength(user: User) {
    val name = user.name
    if (name != null) {
        println(name.length) // ok
    }
}

This is not a “hack”; it is normal style: “read once → check → use”.

Why the compiler is especially cautious with a custom getter

To make it crystal clear why the compiler is not required to trust properties, imagine the getter is actually tricky:

class FlakyUser {
    val name: String?
        get() = if (System.currentTimeMillis() % 2L == 0L) "Neo" else null
}

fun printFlakyNameLen(u: FlakyUser) {
    if (u.name != null) {
        // Even a human cannot guarantee the second call u.name won't produce null
        println(u.name.length)
    }
}

Here you can already see that “check and then use” does not work, because u.name is effectively a function. The compiler behaves strictly so it can be equally safe for both simple and tricky cases.

Nullable + lambda: the value “escapes” your control

Next class of situations: you checked x != null, and then you use x inside a lambda. Sometimes it works, sometimes it does not — and to a beginner it feels like Kotlin is messing with them.

Why? Because a lambda is a separate piece of code that may execute not where you expect. The compiler must be sure the variable will not change before the lambda actually runs.

Example: suppose we format output via a function that accepts an action.

fun render(block: () -> Unit) {
    block()
}

fun printLenInsideLambda(text: String?) {
    if (text != null) {
        render {
            println(text.length) // sometimes smart cast limitations appear here
        }
    }
}

In practice, Kotlin 2.x (the K2 compiler) became better in some smart-cast-inside-lambda scenarios for inline functions, because an inline function behaves as if the lambda is “called right here”, making it easier for the compiler to prove safety. But the basic principle remains: if the compiler cannot guarantee that the lambda runs exactly here and the variable cannot change, it will be cautious.

The most reliable technique that works almost always: take a snapshot before the lambda.

fun render(block: () -> Unit) {
    block()
}

fun printLenInsideLambda(text: String?) {
    val snapshot = text
    if (snapshot != null) {
        render {
            println(snapshot.length) // ok
        }
    }
}

Smart cast and try/catch: when information can “reset”

One more thing that sometimes surprises people: you kind of “already knew” the variable was not null, but inside try/catch or after some operations the compiler can give you the nullable type back.

We do not need to go deep into details right now, but it is useful to understand the principle: if inside try you assign a different value to the variable (including null), the compiler must re-evaluate its type after that. So the “snapshot into val” style again works as a universal safety belt when you want to use the value as stable.

3. Techniques for rewriting code for smart cast

Snapshot into a local val

This is the basic technique for almost all “smart cast impossible” situations: read the value exactly once and then work with it as a local val.

The formula is simple:

val snapshot = maybeNull
if (snapshot != null) {
    // use snapshot as non-null
}

This habit solves two problems at once: it makes code clearer and eliminates repeated reads/getter calls.

Guard clause: early exit so everything after becomes non-null

Sometimes the best way to “convince” the compiler is to make the code more straightforward: if the value is null, we exit immediately. This is called a guard clause. The advantage of this style: less nesting, fewer if “staircases”, and the compiler usually finds it easier to apply smart cast for the remaining part of the function.

Let’s compare two variants.

Variant with nesting:

fun printUpper(text: String?) {
    if (text != null) {
        println(text.uppercase())
    }
}

Variant with early exit:

fun printUpper(text: String?) {
    if (text == null) return
    println(text.uppercase()) // text is treated as String
}

Psychologically, this style often reads easier: first we “cut off bad cases”, then we write the main scenario without constant ?..

requireNotNull / checkNotNull: an explicit conversion T? -> T

When null means “this is a bug / contract violation”, you can avoid coaxing smart cast and instead say it directly: “if it is null — fail with a clear message”. That is what requireNotNull and checkNotNull are for.

The semantic difference is: require* is usually about invalid arguments/input for a function, while check* is about an invalid state (broken invariant). In this lecture the more important part is: both functions return a non-null value, meaning they are a convenient and readable way to get a T.

Example:

fun tokenLength(token: String?): Int {
    val t = requireNotNull(token) { "Token must be provided" }
    return t.length
}

Here we do not even ask smart cast to work: we explicitly performed a “conversion” from String? to String.

But it is important not to overuse this. If token is user input that can be absent in a normal scenario, fail-fast may be too harsh: you will just crash the program instead of asking the user to enter a value again. Preconditions are good where null means “the programmer made a mistake” or “an internal contract was violated”.

4. Practice: the remove command and double-reading the search result

Let’s imagine a learning CLI expense tracker. We have a repository that can find an expense by id. By the search contract the result may be missing — so it is an Expense?.

A very simple model:

data class Expense(val id: Int, val title: String, val amount: Int)

fun findExpenseById(expenses: List<Expense>, id: Int): Expense? {
    return expenses.find { it.id == id }
}

Now the remove command handler in a naive style:

fun handleRemove(expenses: MutableList<Expense>, id: Int) {
    if (findExpenseById(expenses, id) != null) {
        // Bad: we call the search again and hope the result is the same
        val title = findExpenseById(expenses, id).title
        println("Removed: $title")
    }
}

Here the problem is not only smart cast — it is also a logical issue: we search for the element twice. Between calls the list could have changed, and it is also just extra work.

The correct style: find once → store → then work with a “snapshot of the result”.

fun handleRemove(expenses: MutableList<Expense>, id: Int) {
    val found = findExpenseById(expenses, id)
    if (found == null) {
        println("Nothing to remove: id=$id")
        return
    }

    expenses.remove(found)
    println("Removed: ${found.title}") // Removed: ...
}

Notice: this is both a “snapshot” and a guard clause. Code like this is almost always easier for the compiler, faster for the program, and clearer for a human.

5. Cheat sheet: where smart cast works and where it does not

Sometimes it is more useful not to “memorize rules”, but to keep one idea in mind: smart cast is possible when the value is stable. But to make it easier to cross-check, here is a compact table.

Situation in code Why the compiler may refuse What to rewrite
Checked if (x != null) and then use x Usually ok if x is a local val or a parameter Nothing, this is the “ideal” case
var x: T? checked and then used later var can change, especially if it is read twice Make val snapshot = x and work with snapshot
Checked obj.prop != null, and then used obj.prop.something prop is read twice; the getter may return something different val p = obj.prop and then use p
Use inside a lambda after a check The lambda may execute later or in another context Snapshot before the lambda, or ?.let { ... }
Complex code where after the check there is an assignment to the same variable The check may have become outdated Guard clause or snapshot before changes

And yes: in Kotlin 2.x some scenarios started to “pass” better than before (especially together with inline functions and certain conditions), but you still win if you write code in the style “one read → check → use”.

6. Common mistakes

Mistake #1: “I checked user.name != null, so user.name.length is definitely safe”.
This is one of the most common traps, because visually it looks obvious. But property access is not the same as accessing a local variable: it can be a getter, a repeated read, a state change. The fix is almost always simple: val name = user.name, and then work with name.

Mistake #2: “I’ll just quickly put !!, because I’m sure”.
!! is not a solution to the smart-cast problem; it is simply a way to ask the program to crash later and louder. If you are sure null is impossible here by contract, it is better to use requireNotNull/checkNotNull with a clear message. If null is possible — then you must handle that scenario (early return, ?:, ?.let { ... }), rather than turning it into a landmine in the code.

Mistake #3: repeated computations instead of saving the result.
When you write if (find(...) != null) println(find(...).title), you are relying not only on smart cast, but also on the search function being deterministic and state not changing. Even if that is true now, the code becomes less readable and can become a source of bugs during refactoring. The correct style: compute once → put into val found → then work with it.

Mistake #4: “I took a snapshot, but then I still use the original variable”.
Sometimes a developer writes val snapshot = x, checks snapshot != null, and then inside the block accesses x again. This takes you back to the original problem: x is still nullable and potentially mutable. If you made a snapshot — use it consistently.

Mistake #5: turning ?.let { ... } into a nesting doll of let inside let.
let is great, but if you start building a “pyramid” of three nested let, the code becomes heavy again. In such cases it is better to create a few clear intermediate vals, use guard clauses, or carefully split the code into a couple of functions where each one works with already non-null values.

1
Task
Kotlin SELF, level 41, lesson 2
Locked
Message status
Message status
1
Task
Kotlin SELF, level 41, lesson 2
Locked
Attendee badge
Attendee badge
1
Task
Kotlin SELF, level 41, lesson 2
Locked
Report label
Report label
1
Task
Kotlin SELF, level 41, lesson 2
Locked
Header key
Header key
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION