1. Introduction
When you’re just starting out, it feels very tempting to make a model “for all possible cases”: name: String?, category: String?, amount: Int? — and we’ll sort it out later. At that moment you’re literally buying yourself freedom… but on credit, with a huge interest rate. Because every next piece of code will be forced to “pay” with null checks: during output, sorting, calculations, message formatting, and even in the simplest conditions. Kotlin, of course, warns you honestly: nullable types require explicit handling.
How null “spreads” through the program
Imagine that in our console app (we’ll continue the practical example — a hypothetical expense tracker) you store expenses like this:
data class BadExpense(
val amountCents: Int?,
val category: String?,
val note: String?
)
At first it seems: “convenient, you can create an object even from messy input.” But after just a couple of functions it starts:
- “how do you sum an Int??”
- “what do you do if category == null?”
- “can you even print note?”
- “is sorting by category even possible?”
And you start turning the code into a forest of ?:, ?.let {}, if (x == null) return ....
The main idea of this lecture
Nullable on the outside, strict types on the inside.
That is, null is allowed at the boundary (input, external data), but after normalization/validation we should obtain internal objects with no nullable fields.
2. Where null is acceptable, and where it is not
To design without nullable fields, you first need to agree on where null is acceptable at all. Now we’ll do it as pragmatically as possible: not “philosophically,” but “so the code doesn’t get sick.”
In real applications, the null boundary almost always runs where data comes from outside: the user typed a string, an HTTP request arrived, a file was read, data came from a database. Today we’re not touching files/network/DB, but the principle is the same: external input is unpredictable; the internal model must be predictable.
Here’s a simple diagram that’s useful to keep in mind:
flowchart LR
A["Raw input (String? / String)"] --> B["Normalization (trim, lowercase, split)"]
B --> C["Parsing + validation (toIntOrNull, rules)"]
C --> D["Internal model (no null)"]
A table of “what’s allowed and what’s not”
| Program layer | What types are acceptable there | What we consider the norm |
|---|---|---|
| Input (CLI) | String, sometimes String? | Input can be empty/messy |
| Normalization | String? for a short stretch | “Brought into shape,” but not confident yet |
| Parsing/validation | Result<T>, a sealed result, sometimes T? | Errors should be explicit |
| Internal model (domain) | Only non-null (String, Int, enum, …) | If an object is created, it is correct |
3. Internal model: the object is always valid
Now we’ll design a strict expense model for our console tracker. The idea is simple: if the list contains an Expense, then it has an amount, a category, and a note (or at least an empty note — but that decision must be intentional).
We’ll use a data class, because it’s a convenient form for a data model: Kotlin automatically generates useful methods like toString(), equals(), copy(), and destructuring.
Category as an enum, not a String
If the category is a string, you’ll very quickly end up with "Food", "food", "FOOD", "food", "Food", "FoOd" and the mysterious "Foood" (it’s not a new category; it’s a human typo at 3 a.m.).
So in a strict model we’ll make categories an enum:
enum class Category {
FOOD, TRANSPORT, FUN, OTHER
}
A strict Expense without nullable fields
Let’s build the expense model. We’ll store the amount in cents (an integer), because using Double for money is its own horror genre.
data class Expense(
val id: Int,
val amountCents: Int,
val category: Category,
val note: String
) {
init {
require(id > 0) { "id must be positive" }
require(amountCents > 0) { "amountCents must be positive" }
require(note.isNotBlank()) { "note must not be blank" }
}
}
Here we use require(...) as fail-fast: if someone inside the program tries to create an “invalid” Expense, it’s better to crash immediately with a clear message than to carry the error further.
Important: require is not “validating user input” (because we want to handle user input gently). It is protection of the model’s invariants: “such an object must not exist inside the program.”
4. Raw input: a separate type with null
Now we’ll do what we came for: introduce a separate type for raw input. It can be messy, empty, unparsed, partial. And that’s fine, because it’s not a model yet; it’s a draft.
The trick (very useful in real projects): don’t try to create an Expense from input right away. Instead, create a Raw… or …Input, and then convert it to a strict model with a separate function.
RawExpenseInput: data “as is”
data class RawExpenseInput(
val amount: String?,
val category: String?,
val note: String?
)
Looks too simple? Great. Our goal is not a “smart class,” but an honest box containing what came from outside.
Normalization: bring strings into a reasonable form
Normalization is “wash the data and comb it,” but not “trust it” yet. For example, if a string consists of spaces, we treat that as the absence of a value.
fun normalizeText(raw: String?): String? {
val s = raw?.trim()
return s?.takeIf { it.isNotEmpty() }
}
Note: normalizeText returns String?. That’s fine: it still works at the boundary. But next we’ll turn this String? into an explicit result.
5. Parsing: a sealed result instead of null
Now the key point: how to return a parsing/validation result so that:
- there is no null inside the model,
- the calling code understands what went wrong,
- we don’t “swallow” errors with printlns somewhere deep inside.
For a learning project, it’s very convenient to make a sealed class for the result: either Ok or Error (you can name them Invalid, Missing, and so on).
Parsing result: Ok/Error
sealed class ParseExpenseResult {
data class Ok(val draft: ExpenseDraft) : ParseExpenseResult()
data class Error(val message: String) : ParseExpenseResult()
}
And what is ExpenseDraft? It’s an “internally valid expense draft,” but without an id (we usually assign an id when adding to a list/repository).
data class ExpenseDraft(
val amountCents: Int,
val category: Category,
val note: String
)
ExpenseDraft is already strict: no nullable fields. That’s very convenient — from here on, the logic works only with non-null data.
Parsing the amount: from string to Int, in cents
We’ll enter the amount in francs/dollars as an integer “in cents” for simplicity, for example 199 = 199 cents. (Yes, it’s not super user-friendly, but for learning it’s great: we avoid floating-point numbers.)
fun parseAmountCents(text: String): Int? {
val x = text.toIntOrNull()
return x?.takeIf { it > 0 }
}
Here Int? is acceptable, because this is a local boundary function: “failed to parse” or “didn’t pass the rule.”
Parsing the category: from string to Category
fun parseCategory(text: String): Category? {
return when (text.trim().lowercase()) {
"food" -> Category.FOOD
"transport" -> Category.TRANSPORT
"fun" -> Category.FUN
"other" -> Category.OTHER
else -> null
}
}
null here means “the category wasn’t recognized.” That’s a normal boundary contract.
Assembling ExpenseDraft from RawExpenseInput
Now let’s combine everything. This is the “gateway” that doesn’t let null in.
fun parseExpenseDraft(raw: RawExpenseInput): ParseExpenseResult {
val amountText = normalizeText(raw.amount)
?: return ParseExpenseResult.Error("Amount is missing")
val amount = parseAmountCents(amountText)
?: return ParseExpenseResult.Error("Amount must be a positive integer")
val categoryText = normalizeText(raw.category)
?: return ParseExpenseResult.Error("Category is missing")
val category = parseCategory(categoryText)
?: return ParseExpenseResult.Error("Unknown category: $categoryText")
val note = normalizeText(raw.note)
?: return ParseExpenseResult.Error("Note is missing")
return ParseExpenseResult.Ok(
ExpenseDraft(amountCents = amount, category = category, note = note)
)
}
Notice the style: lots of early returns. This makes the code “flat”: there are no giant nested ifs, and each error is returned with a specific reason. The Kotlin approach “nullable values → check → early exit” is absolutely normal practice.
6. CLI scenario: adding an expense without null
Now let’s connect everything into a mini scenario. We have a list of expenses, an add command, and the user enters data. We’ll intentionally keep the example compact so you can keep it all in your head.
Simple id generation
fun nextId(expenses: List<Expense>): Int {
val maxId = expenses.maxOfOrNull { it.id } ?: 0
return maxId + 1
}
maxOfOrNull returns nullable because the list can be empty — this is a normal “collection nullable boundary.” We carefully turn it into 0 via the Elvis ?:, and then we’re back to living with Int, not Int?.
Turning ExpenseDraft into Expense
Here Expense can already apply its require(...) in init. But in a normal scenario it won’t come to that: we’ve already checked everything during parsing.
fun createExpense(expenses: List<Expense>, draft: ExpenseDraft): Expense {
return Expense(
id = nextId(expenses),
amountCents = draft.amountCents,
category = draft.category,
note = draft.note
)
}
Parsing the add command from a line
Suppose the command format is:
add <amountCents> <category> <note...>
For example:
add 199 food coffee
add 500 transport taxi to airport
Let’s make a simple parser (without future topics like Regex validation from day 27). Let note be everything after the first two tokens.
fun rawInputFromAddCommand(line: String): RawExpenseInput {
val parts = line.trim().split(" ")
val amount = parts.getOrNull(1)
val category = parts.getOrNull(2)
val note = parts.drop(3).joinToString(" ").takeIf { it.isNotBlank() }
return RawExpenseInput(amount = amount, category = category, note = note)
}
getOrNull is a very honest way to say: “the element may be missing.” Again: nullable lives at the boundary, and then we’ll “squeeze” it into ParseExpenseResult.
The add command: the full scenario
fun handleAdd(expenses: MutableList<Expense>, line: String) {
val raw = rawInputFromAddCommand(line)
when (val parsed = parseExpenseDraft(raw)) {
is ParseExpenseResult.Error -> println("ERROR: ${parsed.message}")
is ParseExpenseResult.Ok -> {
val expense = createExpense(expenses, parsed.draft)
expenses.add(expense)
println("Added: $expense") // Added: Expense(id=1, amountCents=199, category=FOOD, note=coffee)
}
}
}
Notice: inside handleAdd there is no String?, no Int?, and certainly no Expense?. We work either with Error(message) or with Ok(draft) — and that really unloads your brain.
An empty string instead of null: why a sentinel is dangerous
Sometimes you want to say: “Let’s store note: String instead of note: String?, and if the user didn’t enter anything, we’ll put an empty string.” Formally, this removes nullable. But a new problem appears: an empty string starts to mean “no note,” and you must remember that everywhere.
Sentinel values (like "", 0, "UNKNOWN") are sometimes appropriate, but only if you’re ready to lock them in as a contract and handle them in one or two places, rather than smearing them across the whole project.
In our example we chose a different contract: note is required and cannot be empty, this is checked at the boundary, and inside the model it is protected by require(note.isNotBlank()).
If you really need “note is optional,” it’s better to do it not with a sentinel, but with a separate result variant or a separate field in the raw input layer. For example, RawExpenseInput.note can be null, but when assembling ExpenseDraft you can decide: either it’s an error (like we do), or you substitute a meaningful default.
7. Common mistakes
Mistake #1: making nullable fields in the domain model “just in case.”
This almost always leads to null participating in every operation: calculations, output, filtering, sorting. As a result, you’re writing not “expense tracking,” but “tracking where else null might be.” It’s much more profitable to admit that input data can be messy, but the internal model should not: introduce Raw…, validate, and only then create a strict object.
Mistake #2: returning Expense? from parsing and printing the error reason via println inside.
Then the calling code gets “well, either there’s an object or there isn’t,” but it doesn’t understand why there isn’t one. And the error reason flies into the console somewhere deep inside, mixing with other messages. A result sealed class (Ok/Error) or Result<T> solves this more cleanly: the reason becomes part of the value, not a side effect.
Mistake #3: mixing “input error” and “internal failure” in the same style.
The user can type "abc" instead of a number — that’s an expected situation, and it should be returned as Error("Amount must be..."). But trying to create an Expense(amountCents = -10) from already validated data is more likely a program bug, and require(...) in the model (fail-fast) is appropriate there.
Mistake #4: “we already checked it,” and then still using !!.
!! usually appears when you haven’t agreed on where exactly the null boundary is. In our approach, the boundary is in parsing: while we’re in Raw… and normalization, nullable is acceptable, but after ParseExpenseResult.Ok there should be no reason for !! inside. If your hand reaches for !!, it’s a good signal: either you skipped validation, or you mixed layers.
Mistake #5: making nullable fields in the Ok branch of a sealed result (“Ok, but value may be null”).
This is a sneaky way to return null “wearing a mask.” You end up with Ok(value: T?), and you’re dragging uncertainty inside again. If the result is Ok, it must contain a strict value without null, otherwise the whole idea of a strict model falls apart.
GO TO FULL VERSION