CodeGym /課程 /Kotlin SELF /Why the compiler forbids dangerous code

Why the compiler forbids dangerous code

Kotlin SELF
等級 11, 課堂 2
開放

1. null is not “empty”, it is “no object”

When you are just starting to program, it is very tempting to want “absence” to behave like a normal value—for example, to make null something like an empty string "" or the number 0. But null in Kotlin (and in general on the JVM) means something else: there is no object, which means it has neither properties nor methods. It is like trying to call a person who... has no phone. The number is not “empty”; the phone physically does not exist.

At runtime, the problem looks like this: if you try to access a property or method on null, you get a runtime error (on the JVM—the typical NullPointerException). Kotlin tries to prevent this situation in advance, already at compile time.

To feel the difference, compare “an empty string” and “there is no string”:

fun main() {
    val s1: String = ""
    val s2: String? = null

    println(s1.length) // 0
    println(s2)        // null
}

For s1 the string object exists; its length is just zero. For s2 there is no object at all—so talking about “length” is meaningless.

Danger appears when accessing through the dot .

In Kotlin (as in many languages), the dot . means: “take a property from the object or call its method”. This is so familiar that we do it automatically: name.length, text.uppercase(), number.toString(). And as long as the type is not nullable, it is all fair: the object exists, so you can access it.

But as soon as a value of type T? appears to the left of the dot, a fork appears: the object may exist, or it may be null. And the dot . is ruthless: it cannot “politely ask” whether the object exists. It just tries to access.

Here is a simple example that Kotlin will not let you compile:

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

    println(text.length) // Compilation error: text may be null
}

Why is the compiler against it? Because by contract the string text may be null, and null has no length. And if Kotlin kept silent, the program would have a chance to crash at runtime.

It is important to catch the idea: the danger appears not because of null itself, but because of the “member access” operation (.), which implies the presence of an object.

Type T? means “there are two scenarios”

In Kotlin, the type String? is like a sign on a door: “there may be a person in the room, or there may be nobody”. If you want to talk to someone (call a method or read a property), you must first make sure someone is there. Kotlin forces you to do this, because otherwise you will get a runtime error, often at the worst possible moment.

A typical scenario that looks “innocent” but is actually dangerous is related to parsing numbers:

fun main() {
    val a: Int? = "6".toIntOrNull()
    val b: Int? = "7".toIntOrNull()

    println(a * b) // Compilation error: a and b may be null
}

Here the compiler sees this: a is not Int, but Int?. So instead of “definitely a number”, we have “either a number, or the absence of a number”. But arithmetic is defined for numbers, not for “possibly missing numbers”. Therefore multiplication is forbidden until you decide what to do in case of null.

2. Where nullable values come from in console tasks

User input and toIntOrNull()

Right now we have neither collections, nor classes, nor complex APIs. But even in small console programs, null already appears all the time—because of input. A user can enter anything, including “forty twooo”, an empty string, spaces, or a sudden bit of philosophy instead of an age.

That is exactly why toIntOrNull() appeared in previous lectures: it speaks honestly—“if this looks like a number, I will return a number; otherwise I will return null”.

Let’s look at a minimal example:

fun main() {
    val text = readln().trim()
    val age: Int? = text.toIntOrNull()

    println(age) // if you enter "42" -> 42, if "oops" -> null
}

Here the risk is not that age equals null. The risk starts when we want to do something with age “as with a number”: compare, add, multiply. The compiler stops us earlier than the program can crash and requires: “handle the null case”.

How nullable “spreads” through the code

In practice, the unpleasant feeling appears like this: you did everything right, used toIntOrNull(), got an Int?, and... suddenly half of the operations became “not allowed”. This is not Kotlin being “mean”, it is logic: if a value can be missing, almost every subsequent step must take that absence into account.

For example, you want to calculate how old a person will be next year:

fun main() {
    val ageText = readln().trim()
    val age: Int? = ageText.toIntOrNull()

    val nextYearAge = age + 1 // Error: age may be null
}

The compiler is basically saying: “I’m not against math; I’m against math with emptiness”. And if you think like a human, it is right: if the age did not parse, what does “add 1” mean?

Here it is important to learn to ask yourself a practical question: what should the program do if the value is missing? Usually there are two options:

  • either we consider the input invalid and report an error;
  • or we choose some default behavior (but this requires caution, because a “default age of 0” is a strange idea in real life).

In this lecture we will solve it the first way: an explicit check and a clear message.

3. How to protect yourself without special operators for null

An explicit if check (x == null)

For now we are not introducing special operators for null (they will be in the next lecture), so we act as directly and “honestly” as possible: we write if, check for null, and in each branch we do something meaningful.

Here is an example where we either print the result or explain the error:

fun main() {
    val aText = readln().trim()
    val bText = readln().trim()

    val a: Int? = aText.toIntOrNull()
    val b: Int? = bText.toIntOrNull()

    if (a != null && b != null) {
        println(a * b) // if you enter 6 and 7 -> 42
    } else {
        println("You need to enter two integers.")
    }
}

Pay attention to an important detail: we do not try to “carry” null further through the program. We decide what to do as close as possible to the place where we use it.

Early return keeps the code flat

When there are more checks, the code easily turns into an “if staircase”, where everything shifts to the right, as if the file is slowly sliding off the desk. So a useful technique is an early exit: if the data is bad, we quickly end the scenario (or return from the function), and the “main” logic remains without extra nesting levels.

While we write in main, it looks like this:

fun main() {
    val ageText = readln().trim()
    val age: Int? = ageText.toIntOrNull()

    if (age == null) {
        println("Age must be a number.")
        return
    }

    println("In a year you will be ${age + 1}.") // with input 20 -> In a year you will be 21.
}

Notice how readable it is: first a “guard check”, then normal logic. And the compiler is happy too, because after return we have a scenario where the age definitely exists.

Mini questionnaire: a “soft” age without crashes

So the examples are not a set of disconnected snippets, let’s keep developing the same app idea: a small console questionnaire. Before, it could simply ask for a name and an age. Now we will make it more robust: the age may be entered incorrectly, and the program must not crash.

Let’s make a small function that prints a “nice greeting” if the age is valid, or explains the error if it is not. (We already had functions in previous lectures, so nothing supernatural.)

fun greetUser(name: String, ageText: String) {
    val age: Int? = ageText.trim().toIntOrNull()
    if (age == null) {
        println("Hi, $name! I couldn't understand the age: '$ageText'.")
        return
    }
    println("Hi, $name! You are $age years old.") // for example: Hi, Alex! You are 25 years old.
}

fun main() {
    val name = readln().trim()
    val ageText = readln()
    greetUser(name, ageText)
}

4. Cheat sheet and diagram: how the compiler thinks

What the compiler will require you to prove

Sometimes it helps to think of T? as a type “with a fork”. Then the compiler is not “getting in the way”; it simply forces you to choose a route.

A small table to reinforce the logic:

What you have in your hands What you want to do Why it is dangerous/safe What the compiler will require
String
text.length
the string object definitely exists nothing, it is safe
String?
text.length
text may be null, and null has no length handle null (for example, if)
Int?
age + 1
age may be missing; “add 1 to a missing value” is undefined handle null
Int? after a check
age + 1
in the current branch, the value exists the compiler will allow it

It is also useful to remember that Kotlin does not guess the meaning for you. If you do not decide what to do when you get null, the language will not invent “well, let it be 0”. It honestly asks you to write that explicitly.

Diagram: got T? → compiler stops you → choose behavior

Sometimes it is easier for students to remember not rules, but a route. Here is the route as a simple flowchart:

flowchart TD
    A["Got a value of type T?"] --> B["We want to call a method/read a property (.) or perform an operation"]
    B --> C{"Can the value be null?"}
    C -->|Yes| D["The compiler forbids direct usage"]
    D --> E["Write handling: if (x == null) ... else ..."]
    C -->|No| F["The operation is safe; the compiler allows it"]

Yes, it looks like bureaucracy. But in practice it saves hours of debugging, because “it crashed somewhere over there” turns into “it doesn’t compile right here”, and that is usually much nicer.

5. Common mistakes

Mistake No. 1: treating the compiler message as “the language is broken” instead of a hint about logic.
When Kotlin says you cannot call .length on a String?, it is not nitpicking syntax. It literally says: “you haven’t decided what to do if there is no string”. The best approach is not to argue with the compiler, but to answer the question: “what behavior is correct when null happens exactly here in the program?”

Mistake No. 2: trying to carry null further and “deal with it later”.
Often you want to do: “let age be an Int?, and later I’ll somehow...” — and later everything starts falling apart with type errors. Usually it is simpler and cleaner to handle null closer to the source: parsed → checked → either work with a normal value, or end the scenario/report an error.

Mistake No. 3: making things nullable “just in case”, and then being surprised by restrictions.
If a variable must exist by meaning (for example, a user name in a questionnaire), you do not need to declare it as String? “for the future”. Nullable types should be introduced where a missing value is truly possible and logically acceptable. Otherwise you make your own life harder, and the compiler honestly starts demanding handling where there should not be any.

Mistake No. 4: confusing a “parse error” with the value 0.
Sometimes a student thinks that toIntOrNull() returns 0 on error. But 0 is a normal number, while null means “there is no number”. If you mix these meanings, the program will start accepting invalid input as valid (for example, the age “kitty” turns into 0), and you will get a logical bug that the compiler will no longer catch.

Mistake No. 5: writing a check but not changing behavior.
Sometimes you see code like: “if age == null, then... nothing” and the program continues, running into restrictions again or the need for weird actions. A null check must lead to a decision: either we stop executing the current scenario (early return), or we define a separate behavior branch. Without a decision, the check becomes a decorative “caution” sticker that does nothing.

1
任務
Kotlin SELF, 等級 11, 課堂 2
上鎖
數值加總器
數值加總器
1
任務
Kotlin SELF, 等級 11, 課堂 2
上鎖
依年齡計費
依年齡計費
1
任務
Kotlin SELF, 等級 11, 課堂 2
上鎖
暱稱標準化
暱稱標準化
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION