CodeGym /Courses /Kotlin SELF /Compiler messages about nullability

Compiler messages about nullability

Kotlin SELF
Level 11, Lesson 5
Available

1. Introduction

If you’re just starting out, the compiler can easily feel like a cranky teacher who, instead of “wrong,” writes: “Type mismatch: inferred type is String? but String was expected” — and then rides off into the sunset. But in reality, the Kotlin compiler is pretty honest: it almost always tells you what exactly you’re trying to do and why it’s dangerous. Our goal is to learn to see behind the “scary phrase” a concrete everyday situation: “I might not have a value, but I’m behaving as if I definitely do.”

From today on, we’ll look at nullability messages as hints, not as punishment. In IntelliJ IDEA (especially in K2 mode) it’s even nicer: the IDE highlights the problematic spot and often offers quick fixes.

Main idea: T? is being used as T

When you see errors related to null, it helps to keep a simple model in mind: Kotlin splits values into two “castes.” The first caste contains regular types (String, Int) — they promise: “a value exists.” The second contains nullable ones (String?, Int?) — they honestly warn: “the value might not exist.”

If you try to access members of an object (.length, .uppercase()), pass a value into a function that expects non-null, or do arithmetic, the compiler will ask: “what if it’s null?” And until you answer that question in code, it won’t compile the program.

A quick “thinking flowchart”:

flowchart TD
    A[Got a value of type T?] --> B{What do we do next?}
    B --> C[Check for null and choose a branch]
    B --> D[Use ?. for safe access]
    B --> E[Use ?: to provide a default]
    B --> F[Use !! and risk crashing]
    C --> G[Inside the non-null branch: work as with T]

These aren’t “four different philosophies,” but four different answers to one question: how exactly do we handle the absence of a value.

Translator table: message → cause → typical fix

Compiler messages are scary mainly because they look like “a letter from the tax office.” Let’s turn them into a normal human table. Here are the most common wordings you’ll run into at this stage.

Compiler message (typical) What it means in plain English What to look at in code What usually fixes it
Type mismatch: inferred type is String? but String was expected You’re passing a String? where a String is required Type on the left/right, function parameter type ?: (default), early return, if check (x == null)
Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver You’re calling a method/property on T? as if it were T The place where the dot is: x.something x?.something, or if (x != null) x.something
Operator call corresponds to a dot-qualified call ... which is not allowed on a nullable receiver Same thing, but for operators (+, *) An operation on Int?, Double? Remove nullable: ?:, null check, don’t multiply “maybe-numbers”
Smart cast to 'String' is impossible, because ... The compiler can’t guarantee the value won’t change Usually a var, an object property, or “too far” from the check Snapshot into a val, move usage closer to the check, ?./?:
Unnecessary safe call on a non-null receiver You’re writing ?., but the left side is already non-null The variable type is already T Remove ?. (not an error, just cleanup)

Important: today we’re not “memorizing the message texts.” We’re learning to infer their meaning from the structure: there are almost always hints like expected/found, nullable receiver, smart cast impossible.

2. Fixing algorithm: where you must decide the fate of null

When you see an error, you want to do the fastest thing: slap on !! and “let it burn.” That’s a human impulse—no judgment. But let’s agree: !! is like kicking down a door. Sometimes the door really is locked and you’re a firefighter. But more often you just left the key in another jacket.

Instead, we’ll act using a calm algorithm.

First, find where exactly the nullable came from. At this stage of the course, the most common sources are toIntOrNull() and variables that you explicitly typed as String?/Int?. Then answer the question: what do we want to do if it’s null? In practice there are only a few options: show a message, provide a default, ask for input again, or gracefully stop the scenario.

Only after that do you choose the technique: an if check, safe call ?., Elvis ?:, or in rare cases, !!.

To make it practical, let’s walk through a mini-app that we’ll “grow” with examples.

Mini app: a user form and where errors are born

Imagine a simple program: it asks for a name and age, then prints a greeting. On paper, everything looks nice. In real code, the user types “twenty eight,” extra spaces, or just hits Enter for philosophical reasons.

Let’s start with the straightforward version—it will almost certainly lead you to the compiler messages we’re learning to translate today.

fun main() {
    print("Enter name: ")
    val name = readln().trim()

    print("Enter age: ")
    val age = readln().trim().toIntOrNull()

    println("Hi, $name! You are $age years old.")
    // Example output: Hi, Alice! You are 28 years old.
}

At first glance—fine. But the type of age here is Int?, and that starts “infecting” the rest of the code: you print “you are null years old,” and if later you want to compare the age or do math, the compiler will start protesting.

And that’s the core point: compiler messages appear not “because Kotlin is mean,” but because you haven’t made a decision yet: what to do on invalid input.

3. Error #1: Type mismatch ... String? vs String

You’ll see this message very quickly when you try to return a nullable value where you promised non-null.

For example, you decide to write a function that “normalizes a name”:

fun normalizeName(raw: String?): String {
    return raw?.trim()
}

This won’t compile, and you’ll see an error roughly like:

Type mismatch: inferred type is String? but String was expected

Why? Because raw?.trim() is a String?. If raw == null, the result is also null. But in the signature you promised to return a String (meaning “the string definitely exists”).

The fix depends on intent. The simplest (and often correct for UI/output) option is to provide a default with Elvis:

fun normalizeName(raw: String?): String {
    return raw?.trim() ?: "Unnamed hero"
}

fun main() {
    println(normalizeName("  Alice  ")) // Alice
    println(normalizeName(null))        // Unnamed hero
}

Notice the essence of the error: the compiler isn’t asking you to “add !!.” It’s asking you to decide what to do if raw is missing.

The same principle works with numbers too:

fun parseAge(raw: String): Int {
    return raw.trim().toIntOrNull()
}

Here you’ll get: Type mismatch: inferred type is Int? but Int was expected.

Again, the solution is about meaning. If you believe that on an invalid age it’s acceptable to substitute 0 (not always logical, but sometimes acceptable), then:

fun parseAge(raw: String): Int {
    return raw.trim().toIntOrNull() ?: 0
}

fun main() {
    println(parseAge("42"))     // 42
    println(parseAge("oops"))   // 0
}

But if 0 “masks the problem,” it’s better to return Int? and force the caller to decide what to do. But that’s a different contract—and the compiler is specifically making you choose the contract consciously.

4. Error #2: Only safe (?.) or non-null asserted (!!.) calls are allowed...

This message usually appears when you do something like:

fun main() {
    val nickname: String? = null
    println(nickname.length)
}

null has no length (it isn’t a String object at all), so Kotlin won’t let you write code that can potentially crash.

Decoding the error: you’re trying to call a member (length) on a value that might be missing. How you fix it depends on intent again.

If “well, no value means no value” is fine, use a safe call:

fun main() {
    val nickname: String? = null
    val len: Int? = nickname?.length
    println(len) // null
}

If you need a guaranteed Int, add Elvis:

fun main() {
    val nickname: String? = null
    val len: Int = nickname?.length ?: 0
    println(len) // 0
}

If you need one behavior when a nickname exists and another when it doesn’t, an if check is often more readable:

fun printNicknameInfo(nickname: String?) {
    if (nickname == null) {
        println("No nickname") // No nickname
        return
    }
    println("Nickname '$nickname', length = ${nickname.length}")
}

fun main() {
    printNicknameInfo(null)
    printNicknameInfo("neo")
}

What matters here is that after return the compiler understands: beyond that point, nickname is definitely not null. That’s smart cast in a “linear style.”

5. Error #3: nullable arithmetic and operators

Sometimes you don’t write a dot—you write a + b—and still get a message about a nullable receiver. This can be surprising: “I didn’t call a method!” But in Kotlin many operators are syntactic sugar over function calls.

For example:

fun main() {
    val a: Int? = "10".toIntOrNull()
    val b: Int = 5

    val sum = a + b
    println(sum)
}

This won’t compile because a is an Int?. And plus (what’s behind +) expects a regular Int on the left.

The fix is, again, to “remove nullable.” The most direct option: provide a default.

fun main() {
    val a: Int = "10".toIntOrNull() ?: 0
    val b: Int = 5

    val sum = a + b
    println(sum) // 15
}

Or, if you want to terminate the scenario on error:

fun main() {
    val aOrNull = "oops".toIntOrNull()
    if (aOrNull == null) {
        println("Not a number") // Not a number
        return
    }

    val sum = aOrNull + 5
    println(sum)
}

Notice the characteristic pattern: val x = ... ?: return. It helps keep code flat, without extra nested ifs.

6. Error #4: Smart cast ... is impossible

This is the most annoying message, because you seem to have done everything right: you checked for null, but the compiler still says “can’t.”

A classic example is a var:

fun main() {
    var text: String? = "hi"

    if (text != null) {
        println(text.length) // sometimes this is exactly where the compiler may start arguing in more complex cases
    }
}

In the simple case, the compiler will allow it. But make the picture slightly more complex (for example, change text between the check and usage), and the trust disappears:

fun main() {
    var text: String? = "hi"

    if (text != null) {
        text = null
        println(text.length) // not allowed anymore
        println(text?.length)   // allowed
    }
}

Translation of the smart cast error: the compiler can’t guarantee the value stayed the same.

One of the simplest ways to “restore trust” is to take a snapshot into a val (an immutable reference) and work with it:

fun main() {
    var text: String? = "hi"
    val snapshot: String? = text

    if (snapshot != null) {
        println(snapshot.length) // 2
    }
}

This trick can look almost silly (“why copy a variable into a variable?”), but it’s powerful: you freeze the value at a point in time and then work with something that can’t be reassigned.

7. Building the form like an adult

Compiler warnings: not “scolding,” but helping

Errors stop the build. Warnings don’t, but they often hint that your code could be cleaner.

A very typical one: you’ve already made a variable non-null, but out of habit you keep writing ?..

fun main() {
    val name: String = "Alice"
    println(name?.length) 	 // warning: unnecessary safe call
    println(name.length)     // 5
}

This warning isn’t nitpicking. It says: “you’re already in the safe zone; you don’t need to wear a helmet.”

Another example: when Elvis is meaningless:

fun main() {
    val x: Int = 10
    val y = x ?: 0 // this won’t compile at all: x is not nullable
    println(x) // 10
}

Here the compiler won’t let you use ?:, because the left side isn’t T?. That’s also a useful guard: Elvis is a tool specifically for nullable branches.

Form: types are clear, branches are explicit

Now let’s return to our form and implement it so the compiler is happy and the behavior on errors is predictable.

Let’s set this rule: the name must be non-empty, and the age must be a number. If the age isn’t a number, we print a message and end the program.

fun main() {
    print("Enter name: ")
    val name = readln().trim()

    if (name.isEmpty()) {
        println("Name cannot be empty") // Name cannot be empty
        return
    }

    print("Enter age: ")
    val age = readln().trim().toIntOrNull() ?: run {
        println("Age must be a number") // Age must be a number
        return
    }

    println("Hi, $name! You are $age years old.") // Example: Hi, Alice! You are 28 years old.
}

Notice two things.

First, age here becomes Int, not Int?, because ?: either yields a number or terminates the program. That means no arithmetic or comparisons later will be “infected” by nullable.

Second, we explicitly chose the behavior on error. And that’s exactly what the compiler was asking you to do all along—it just phrased it in bureaucratic language.

When !! is appropriate and why the compiler keeps trying to talk you out of it

Since we keep saying “don’t fix everything with !!,” let’s be honest: !! doesn’t exist for decoration. It’s for cases where you consciously choose the contract “if this is null, that’s a program error.”

For example, you made an internal variable nullable only because that’s how it came from an API, but by your scenario logic it must be set by this point. Then !! becomes a “guard dog”: if the logic is violated, the program fails immediately.

But in educational console scenarios with user input, !! is almost always a bad idea: the user doesn’t have to follow your contract—they’re just living their life.

Mini example (how it looks and why it’s risky):

fun main() {
    val ageText = readln().trim()
    val age = ageText.toIntOrNull()!!
    println("age = $age")
}

This compiles, but if the input isn’t a number, the program crashes. The compiler warned you, and you ignored it. At minimum, do this only when crashing really is the desired behavior.

8. Typical mistakes

Mistake #1: “making it compile” instead of fixing the logic.
Often a beginner sees red highlighting, adds ?: 0 or !!, and is happy that it “works.” But meaning-wise, the program starts lying: age becomes 0, name becomes “anonymous,” and the user gets weird results without an explanation. The right approach is to decide what to do on null first, and only then choose the operator.

Mistake #2: confusing null and an “empty value.”
null means “no value,” while "" means “a string exists, but it’s empty.” If you agreed that an empty string is invalid for a name, that’s not a reason to make it String?. That’s a reason to check isEmpty()/isBlank() and show a message. Nullable doesn’t replace validation.

Mistake #3: smearing null handling across the entire codebase.
If you got an Int? from toIntOrNull() and then dragged it through five functions, you’ll get five places where the compiler will “remind” you about nullable. It’s much easier to handle null close to where it appears: convert Int? into Int via ?: or terminate the scenario. Then the rest of the code becomes simpler.

Mistake #4: hoping smart cast lasts “forever.”
The check if (x != null) makes x safe only within a clear scope and only while the compiler is sure x won’t change. If x is a var, if you move far away from the check, or if the value can change, smart cast breaks. In those cases, either ?./?: helps, or taking a “snapshot” into a val.

Mistake #5: using ?. as if it “provides a default.”
?. doesn’t provide anything. It just returns null if the left side is null. If you need a default (for example, length 0), that’s the job of ?:. Confusing these roles leads to chains like val x = text?.length and unexpected null later in the program.

1
Task
Kotlin SELF, level 11, lesson 5
Locked
Chat name
Chat name
1
Task
Kotlin SELF, level 11, lesson 5
Locked
Nickname length
Nickname length
1
Task
Kotlin SELF, level 11, lesson 5
Locked
Entrance checkout
Entrance checkout
1
Task
Kotlin SELF, level 11, lesson 5
Locked
Note cache
Note cache
1
Survey/quiz
Null-safety, level 11, lesson 5
Unavailable
Null-safety
Null-safety
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION