1. Diving into null
When you see String?, a beginner’s brain often reads it as: “it can be null, so I should put ?. and move on.” But for program design, a more useful reading is different: String? is the author’s promise (of the function/field) that the absence of a value is a normal, expected outcome. And this is where the grown-up part starts: if null is a normal outcome, its meaning should be as clear as the meaning of true/false or 0/1.
Let’s lock in the idea with a simple example. In Kotlin tutorials, people often show a parser: if the string is not a number, return null. That’s an honest contract: “couldn’t parse it — here’s the signal, no exceptions and no mystery.”
fun parsePort(raw: String): Int? {
val trimmed = raw.trim()
return trimmed.toIntOrNull()
}
fun main() {
println(parsePort("8080")) // 8080
println(parsePort("oops")) // null
}
Here null means a specific thing: “the string does not contain a valid integer.” This is not a system error, not a bug, not “something went wrong” — it’s a normal situation at the input boundary.
Now imagine you did this:
fun loadConfigText(): String? {
// ... reading something
return null
}
And that’s it. What does null mean? Config not found? No permissions? Empty file? Did you forget to finish the function? That’s already a bad contract: it forces the caller to guess.
Key criterion: if you put ?, you must answer the question “why might the value be absent?” in a way that doesn’t look like “because I’m too lazy.”
2. Where null is usually justified: program boundaries
Usually null is a great tool at the system boundaries. Where you meet the unpredictable world: user input, command-line arguments, network data, file reads, key lookups (when an element can genuinely be absent). At the boundary, the world has the right to bring you emptiness, a weird string, and “I didn’t enter anything at all.” And that’s where null fits.
In Kotlin, even basic collection operations hint at this approach: for example, reading by key from a Map returns V?, because the key might not exist, and that’s a normal scenario. In such a place, null reads as “not found,” not as “broken.”
Let’s take an example closer to our practical console app (let’s call it ExpenseTracker: a small CLI expense tracker). Suppose we have a list of expenses and we look up an expense by id. It’s perfectly fine to return Expense?: the expense could have been deleted, the id could be wrong, or the user could have mistyped it.
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 }
}
fun main() {
val expenses = listOf(
Expense(id = 1, title = "Coffee", amount = 300),
Expense(id = 2, title = "Book", amount = 1200),
)
val e = findExpenseById(expenses, 2)
println(e?.title) // Book
}
Notice: the contract reads perfectly. Expense? here means “may not be found.” And that’s not an “error”: it’s part of the domain.
3. Where null starts to get in the way: inside the model and business logic
Inside the program (after the data has already been recognized and validated), null often turns into a “thin layer of chaos.” The reason is simple: null starts to leak through layers of code. One nullable field pulls in a second, then a third; then you get ?. in formatting, ?: in calculations, if (x != null) in three different places, and at the end — the philosophical question “what even counts as a valid object?”
Let’s imagine a bad version of our expense model:
data class ExpenseDraft(
val title: String?,
val amount: Int?
)
fun main() {
val draft = ExpenseDraft(title = null, amount = null)
println("title=${draft.title}, amount=${draft.amount}") // title=null, amount=null
}
From the outside, it looks convenient: “you can create at least something.” But next you’ll want to:
- display the expense to the user,
- calculate totals,
- sort,
- group.
And everywhere you’ll be thinking: “can this be null here?” It’s like carrying an umbrella at home in the kitchen “just in case”: formally you can, but cooking becomes uncomfortable.
An important idea of today’s lecture: nullable fields inside a “normal” model often mean you mixed different data stages. There is “raw input” and there is a “valid entity.” If you mix them in one type, null will spread quickly.
4. Two meanings of null: “no data” and “error”
This part is especially important, because this is exactly where the nastiest bugs begin — not the ones that crash immediately, but the ones that quietly corrupt logic.
null is usually used in two different situations:
| Situation | What it means conceptually | Is it OK to return null? | Example |
|---|---|---|---|
| No value | The value may not exist and that is expected | Yes | “not found by id”, “empty input”, “number didn’t parse” |
| Error / impossibility | We wanted the value, but didn’t get it due to a problem | Risky | “failed to read file”, “network error”, “logic broke” |
The problem is that both situations technically look the same: “returned null.” But conceptually they are as different as “the store is out of bread” and “the store burned down.”
Let’s deliberately make a bad example and see why it’s bad:
fun loadUserName(userId: Int): String? {
// Imagine there could have been a database error here,
// but we just returned null
return null
}
The calling code now can’t distinguish:
- there really is no user with this id (fine),
- the user exists but the DB went down (not fine),
- the developer forgot to implement the function (also not fine).
And then, as a rule, someone writes:
val name = loadUserName(10) ?: "UNKNOWN"
println("Hello, $name") // Hello, UNKNOWN
And there it is — a “silent bug”: the program kept running, but the meaning of the data got corrupted. This is more dangerous than a crash, because a crash at least honestly screams: “I’m in trouble.” But "UNKNOWN" can end up in a report, in an export, in final sums, and further down the chain.
Today’s goal is to learn to spot such places and not use null as a universal “plug for everything.”
5. Practice: how to keep null under control
Criterion: “Can I explain null in one sentence?”
To avoid turning design into philosophy, a very practical test helps.
If a function/field has type T?, try to add a one-line comment to it without feeling awkward. Not a paragraph, not “well, generally…”, but one sentence.
For example, good options:
- findExpenseById(...) : Expense? — “returns the expense or null if not found”.
- parseAmount(...) : Int? — “returns the amount or null if the string is not an integer”.
- normalizeTitle(...) : String? — “returns a trimmed string or null if the string is empty after trim”.
And here are bad options that should raise a red flag:
- “returns null if something went wrong”
- “returns null in case of an error”
- “may return null, I’m not sure”
If you catch yourself using such wording, you are almost certainly trying to hide in null something that conceptually is an error or a separate state.
ExpenseTracker: making contracts readable
We won’t add “advanced” constructs and new result types now (that’s a separate topic for upcoming lectures). Instead, we’ll practice choosing T vs T? correctly and making the contract clear.
Normalizing user input: String? is appropriate
A user can enter an empty string, a string of spaces, or even “press Enter and say nothing.” This is a classic boundary. Here null is honest.
fun normalizeNonEmptyText(raw: String): String? {
val s = raw.trim()
return if (s.isEmpty()) null else s
}
fun main() {
println(normalizeNonEmptyText(" hello ")) // hello
println(normalizeNonEmptyText(" ")) // null
}
null here means “after normalization there is no text.” That is absence of data, not an error.
Parsing a number: Int? is appropriate
Kotlin directly nudges you toward this style: toIntOrNull() returns nullable because parsing is not always possible. This is an example of an “expected failure,” and it’s good.
fun parseAmount(raw: String): Int? {
val s = raw.trim()
return s.toIntOrNull()
}
fun main() {
println(parseAmount("1200")) // 1200
println(parseAmount("12o0")) // null
}
Collection lookup: Expense? is appropriate
This is “not found.” A normal story.
fun removeExpenseById(expenses: MutableList<Expense>, id: Int): Boolean {
val found = expenses.find { it.id == id } ?: return false
expenses.remove(found)
return true
}
fun main() {
val expenses = mutableListOf(
Expense(1, "Coffee", 300),
Expense(2, "Book", 1200),
)
println(removeExpenseById(expenses, 2)) // true
println(removeExpenseById(expenses, 99)) // false
}
Here I intentionally did it so that Expense? doesn’t leak out. The “remove” function uses nullable lookup internally, but externally it returns a simple and clear result: Boolean (“removed / not removed”). This is also part of the culture: keep nullable close to where it originated, and return a more convenient contract to the outside if you can.
Anti-pattern: making everything nullable “so the compiler complains less”
It’s very tempting: the compiler complains that you’re accessing a nullable — and you go: “fine, I’ll make everything nullable, and let the world burn.” In the short run it feels easier. In the long run it turns the code into a quest: “find the place where someone forgot ?..”
To feel the difference, compare two formatting approaches:
fun formatExpenseBad(title: String?, amount: Int?): String {
val safeTitle = title ?: "UNKNOWN"
val safeAmount = amount ?: 0
return "$safeTitle: $safeAmount"
}
fun main() {
println(formatExpenseBad(null, null)) // UNKNOWN: 0
}
On the one hand, the program doesn’t crash. On the other, the data has already been substituted. 0 is not “no amount,” it is “amount zero,” and now the report may become false.
If in your app 0 is a valid expense (for example, a promo code, discount, or refund), you can no longer distinguish “empty” from “zero.” And this is exactly why null is a meaning contract, not “just absence of a value.”
Sentinel values instead of null: why they are dangerous
Sometimes developers say: “I don’t like null, let’s use -1 instead.” Such a value is called a sentinel: a special number/string that means “there is nothing.”
This can work, but there is a risk: you add a hidden agreement into the code. If you forget to check -1 in one place, the logic breaks, but the compiler won’t help you because the type is still Int.
Let’s see a small example where the error looks “reasonable,” but the meaning is already wrong:
fun parseAmountOrMinusOne(raw: String): Int {
return raw.trim().toIntOrNull() ?: -1
}
fun main() {
val amount = parseAmountOrMinusOne("oops")
println(amount + 100) // 99 (and this looks as if everything is fine)
}
That’s why Kotlin promotes nullable: Int? forces you to handle the “no value” case explicitly, while -1 lets you accidentally forget.
This does not mean sentinels are always evil. It means that if you use them, you must make it a contract, not a “quiet trick.”
One processing “gate” instead of smearing null everywhere
In good code, you can often see a style: null lives in one place, near input or lookup, and then it either turns into a concrete action or gets cut off. In bad code, null seeps into all levels: the domain model, reports, formatting, sorting.
Schematically, it looks like this:
flowchart LR
A["External world (input, lookup, data)"] -->|may be null| B["Gate: normalization/validation"]
B -->|non-null| C["Internal logic (model, calculations)"]
B -->|no value| D["Clear reaction (message/branch/exit)"]
The idea is to have fewer places in your code where you reinvent “what should I do with null?” each time. Let it be solved in one clear place.
For example, when parsing a command:
data class AddExpenseCommand(val title: String, val amount: Int)
fun parseAddCommand(line: String): AddExpenseCommand? {
val parts = line.trim().split(" ")
if (parts.size < 3) return null
val title = parts[1].trim().ifEmpty { return null }
val amount = parts[2].trim().toIntOrNull() ?: return null
return AddExpenseCommand(title = title, amount = amount)
}
fun main() {
println(parseAddCommand("add coffee 300")) // AddExpenseCommand(title=coffee, amount=300)
println(parseAddCommand("add coffee oops")) // null
}
Here null means a specific thing: “the command is invalid.” And it’s important that null didn’t leak further. We did not make AddExpenseCommand(title: String?, amount: Int?). We either returned a valid command, or null as the signal “not recognized.”
Nullable receiver in extension functions: localizing checks
Sometimes you want to make a small utility that can work even when the value is null. Kotlin lets you write extension functions on a nullable type (Any?, String?, etc.). This is useful when you want to hide a repeated check in one place instead of writing it at every call site. The official Kotlin documentation shows this too: an extension on Any? can return the string "null" instead of crashing, and inside the body, after checking this == null, the compiler already knows that this is not null.
For our app, we can do something very simple — safe text rendering:
fun String?.toUiText(): String {
return this?.trim()?.takeIf { it.isNotEmpty() } ?: "<empty>"
}
fun main() {
val a: String? = " hello "
val b: String? = " "
val c: String? = null
println(a.toUiText()) // hello
println(b.toUiText()) // <empty>
println(c.toUiText()) // <empty>
}
Notice the subtle line: this is appropriate in UI/output, but not always appropriate in calculations and data storage. Inside the model, "<empty>" would be a strange “sentinel,” but for printing to the console it’s a normal, conscious choice.
6. Typical mistakes when working with null
Mistake #1: making model fields nullable “just in case.”
Most often this happens because you want to “create the object faster.” As a result, the object becomes easy to create but hard to use: in every place you have to remember ?. and invent what to do about absence. Usually this is a sign that you mixed “raw input” and a “valid entity” into one type.
Mistake #2: returning null both for “not found” and for “error.”
Such a contract forces the calling code to guess the reason, which means it will either start “silently fixing” everything via ?:, or start crashing with !!, or just print "UNKNOWN" and corrupt the data. If you catch yourself saying “we’ll return null if something went wrong,” it’s almost always a signal that the contract is vague.
Mistake #3: treating null-contract design with the !! operator.
!! is sometimes needed, but in a real project it often turns into “I’m tired of thinking.” The problem is that you did not resolve the question of meaning: you just moved the crash to runtime. In the context of “nullable as a contract,” it looks like: “the contract says the value may be absent, but I pretend it’s present.”
Mistake #4: replacing null with sentinels (0, -1, "UNKNOWN") without a strict agreement.
If you substitute a “default” value, you change the meaning of the data. Sometimes this is appropriate (especially for UI), but if it’s done without a single policy and without understanding the domain, you get silent logical errors: sums are calculated “almost correctly,” reports look “almost normal,” and then the user asks why they have an expense "UNKNOWN: 0".
Mistake #5: smearing null across the pipeline instead of having one processing gate.
When null passes through 5–10 functions, you lose control: where exactly did it appear, and what does it mean? It’s much more robust when null lives next to its source (input/lookup) and quickly turns into a clear decision: “ask again,” “not found,” “invalid command.”
GO TO FULL VERSION