CodeGym /Courses /Kotlin SELF /What to use instead of null: preconditions, sealed result...

What to use instead of null: preconditions, sealed results, Result

Kotlin SELF
Level 41, Lesson 1
Available

1. Why replace null if we have null-safety

If you write software long enough, you notice one tricky thing: null is not only “there is no value”. In practice, null often starts to mean “something went wrong, but I can’t be bothered to explain”. And that’s where the magic begins: the calling code receives T? and now has to guess what it was — “not found”, “not entered”, “parse error”, “access denied”, or “the developer forgot to implement it”. Kotlin protects us from NPEs, but it cannot protect us from foggy contracts.

Imagine you have a function findExpenseById(id): Expense?. This is a good and honest contract: an expense with that id may not exist. But if you have a function saveExpense(expense): Expense?, and it returns null for any problem, that’s already a “black box”: why null? what should we do next? retry? show a message? crash? And what’s especially unpleasant is that you won’t learn any of this from the signature.

In this lecture we discuss three practical replacements for null, and each answers a specific question:

  • preconditions (require, check, requireNotNull, checkNotNull) answer the question “is it even valid to call this like that?”;
  • sealed results answer the question “what meaningful outcomes can this operation have?”;
  • Result<T> answers the question “how do I return success/error as data, without turning everything into exceptions and without losing the cause?”.

2. Preconditions: require, check, and *NotNull

Preconditions are not “validation of user input”, but protection of your function’s contract. It’s a way to say: “If bad data got here, this is not a ‘real-life situation’, it’s an API misuse error (or a bug in the code above). I’d rather fail immediately with a clear message than carry garbage further and break 20 lines later in a weird place.”

That’s why preconditions most often live inside domain logic, where there “shouldn’t be bad data anymore”, and at boundaries between layers, where you want to sharply separate the “raw world” from the “strict world”.

require(...): validate arguments

A small “meaning cheat sheet”: require means “you called the function incorrectly”. It throws IllegalArgumentException.

Let’s imagine our training CLI project (the course’s hands-on project) — an expense tracker. We have a model:

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

Suppose a domain function creates an expense. We want to guarantee that you cannot create an expense with an empty title and a negative amount:

fun createExpense(id: Int, title: String, amountCents: Int): Expense {
    require(id > 0) { "id must be positive" }
    require(title.isNotBlank()) { "title must not be blank" }
    require(amountCents > 0) { "amountCents must be positive" }

    return Expense(id = id, title = title.trim(), amountCents = amountCents)
}

What matters here is that require is not “handle gently”. It is “stop the program because someone clearly made a mistake”. If you’re thinking “But you can’t crash because of user input!” — you’re right. But this is not about input. This is about the layer where input should already have been validated.

check(...): validate state and invariants

check means “my program ended up in an impossible state”. It throws IllegalStateException. In real life, check is often used when an object has already been created and is supposed to be correct, but you want to guard against a logic error.

For example, we have an expense repository that stores a list. We expect ids to be unique. If we find two expenses with the same id, that’s not a “user error”, it’s a bug in our logic:

fun findUniqueById(items: List<Expense>, id: Int): Expense? {
    val matches = items.filter { it.id == id }
    check(matches.size <= 1) { "BUG: duplicate id=$id found (${matches.size} items)" }
    return matches.firstOrNull()
}

Yes, this still returns Expense?, because “not found” is a normal situation. But at the same time, we protect the invariant “there must be no duplicates”.

requireNotNull and checkNotNull: converting T? → T without !!

A very common pain point: you received a String? (for example, from parsing or from Map.get()), but at this point it must be non-null. Instead of !!, it’s better to use requireNotNull/checkNotNull — because they not only turn T? into T, but also let you write a human-friendly message.

fun normalizeCommand(raw: String?): String {
    val text = requireNotNull(raw) { "Command line must not be null" }
    return text.trim()
}

Unlike raw!!, here, if it crashes you will see a meaningful reason rather than “NullPointerException somewhere over there”.

Elvis and Nothing: “either a value, or we crash”

Another useful pattern is “Elvis + a function that always crashes”. This connects the topic of preconditions with the Nothing type: an expression throw ... has type Nothing, so it works great on the right side of Elvis. In the Kotlin docs, this is shown with fail(message): Nothing, which always throws an exception.

3. sealed results instead of null

Sometimes the problem is not that “there is no value”. The problem is that an operation can have multiple outcomes, and each one is meaningful. If you encode everything via null, you lose meaning and force the caller to guess.

sealed class lets you make the contract: “there is always a result, but it can be different”. And Kotlin forces you to handle all variants (an exhaustive when) if you don’t leave yourself an escape hatch with else.

Deletion by id: several normal outcomes

Deleting an expense is a great example: different outcomes are possible. For example:

  • deleted successfully;
  • no such id;
  • invalid id (for example, <= 0) — and this is more of an API misuse error.

We’ll guard an invalid id with require, and we’ll express “no such expense” as a result variant.

sealed class RemoveExpenseResult {
    data object Removed : RemoveExpenseResult()
    data object NotFound : RemoveExpenseResult()
}

fun removeExpenseById(items: MutableList<Expense>, id: Int): RemoveExpenseResult {
    require(id > 0) { "id must be positive" }

    val index = items.indexOfFirst { it.id == id }
    if (index == -1) return RemoveExpenseResult.NotFound

    items.removeAt(index)
    return RemoveExpenseResult.Removed
}

Notice: there is no null here at all. A concrete meaning is returned.

Now the CLI layer can produce a nice user message:

fun describeRemove(result: RemoveExpenseResult, id: Int): String = when (result) {
    RemoveExpenseResult.Removed -> "Removed expense id=$id"
    RemoveExpenseResult.NotFound -> "No expense with id=$id"
}

The when is exhaustive because sealed closes the set of variants. If you add a new variant, the compiler itself will remind you where you forgot to handle it. It’s a kind of “quality alarm clock” that you can’t ignore (unlike a comment TODO handle errors later).

The Ok/Error pattern, but without T? inside Ok

Many people like the Ok/Error pattern. It’s convenient, but there’s a typical trap: make Ok(value: T?). Then you’re dragging nullability into “success” again, and the whole idea is lost.

Let’s make a result for adding an expense to the repository. Suppose duplicate ids are forbidden.

sealed class AddExpenseResult {
    data class Ok(val added: Expense) : AddExpenseResult()
    data class Error(val message: String) : AddExpenseResult()
}

fun addExpense(items: MutableList<Expense>, expense: Expense): AddExpenseResult {
    val exists = items.any { it.id == expense.id }
    if (exists) return AddExpenseResult.Error("Expense with id=${expense.id} already exists")

    items.add(expense)
    return AddExpenseResult.Ok(added = expense)
}

Here, Ok is guaranteed to contain a non-null Expense. And Error carries the error text as data (not as a println inside the function — we’ll discuss that later in “common mistakes”).

Why sealed is better than null for “error/not found”

The most common reason to choose sealed instead of T? — is when you have two different meanings of absence:

  • “not found” (normal);
  • “error” (must be reported, possibly with a reason).

If you use Expense?, you won’t be able to distinguish “not found” from “couldn’t due to a validation/logic error”. Sure, you can “print to the console” — but then the function becomes untestable and noisy. It’s better to return the meaning in types.

4. Result<T>: error as a value

Result<T> is Kotlin’s standard container: either success with a T, or failure with a Throwable. It’s useful where an error is naturally expressed as an exception (for example, parsing a number via toInt()), but you want to return it as data, without writing try/catch everywhere.

Essentially, it’s a compromise: you don’t give up exceptions as a mechanism (they are still inside), but you expose a neat “success/error” contract to the outside.

Parsing: Result<Int> instead of Int?

In the early days of the course, we often did toIntOrNull() and got an Int?. That’s fine when the only thing you need is “worked/didn’t work”. But sometimes the reason matters: empty string? not a number? too large? negative? And you want to distinguish these.

Result lets you keep the exception and add your own checks via mapCatching.

fun parsePositiveInt(raw: String): Result<Int> {
    return runCatching { raw.trim().toInt() }
        .mapCatching { value ->
            require(value > 0) { "Expected a positive integer" }
            value
        }
}

There’s an important detail: we use require inside mapCatching, and if the condition is not met, that also ends up as Failure. This is convenient because the caller gets a single format for handling.

Result in the CLI layer of the expense tracker

Imagine the command looks like this: add <id> <title> <amountCents>. We read a line, split it, and try to parse it.

fun parseAddArgs(parts: List<String>): Result<Triple<Int, String, Int>> {
    return runCatching {
        val id = parts[1].toInt()
        val title = parts[2]
        val amount = parts[3].toInt()
        Triple(id, title, amount)
    }
}

Yes, IndexOutOfBoundsException or NumberFormatException can be thrown here, and they will neatly end up inside Result.

Next, we convert this result into a clear message:

fun describeParse(result: Result<Triple<Int, String, Int>>): String {
    return result.fold(
        onSuccess = { "Parsed: id=${it.first}, title=${it.second}, amount=${it.third}" },
        onFailure = { "Bad command arguments: ${it.message ?: "unknown error"}" }
    )
}

This is an example where Result is useful exactly at the input boundary: we want to not crash, but also not stay silent.

Why Result<T?> is almost always a bad idea

The combination Result<T?> means: “the operation could fail, and if it didn’t fail, the value might still be absent”. This is rarely a good contract, because you create two independent axes of uncertainty: first figure out whether there was an exception, then figure out why null.

Usually it’s better to choose one:

  • if “may be absent” — use T? or a sealed Found/Missing;
  • if “may break” — use Result<T> or a sealed Ok/Error.

And only if you really need to distinguish “success, but empty” from “error” (for example, a cache lookup: the entry might not exist, but that’s not an error) — then Result<T?> is sometimes justified. But that’s a decision that requires very clear contract documentation.

5. How to choose an approach

When you first start replacing null, a new danger appears: replacing it everywhere at once and making the code “too clever”. So it’s useful to keep a simple selection scheme in mind: what exactly does “no value” mean in your situation, and who is at fault — the user or the programmer.

Below is a practical table (not an “academic truth”, but a working guideline):

Situation Best tool Why
Inside the code, this value must be present (violation = bug/incorrect call)
require* / check*
Fail-fast: crash immediately in an understandable place
The operation has multiple meaningful outcomes (found/not found, ok/error, access denied, conflict)
sealed class
Types force you to handle all variants; you don’t lose meaning
The error is naturally expressed as an exception, but you want “error as data”
Result<T>
Convenient at boundaries; we keep the
Throwable

Now an important architectural idea: these approaches can be combined, but you should do it by layers.

In our expense tracker this looks logical: parsing user input returns Result, because input is dirty and unpredictable. A domain operation returns a sealed result, because meaningful outcomes matter there (“duplicate id”). And preconditions protect invariants and function contracts where “this should not happen”.

Putting everything together into one scenario

Now we’ll assemble the pieces into a small flow. Suppose we have a command to add an expense. We parse input via Result, create the model via require-based protection, and return a sealed result from the repository.

fun handleAddCommand(items: MutableList<Expense>, parts: List<String>): String {
    val parsed = parseAddArgs(parts)
    return parsed.fold(
        onSuccess = { (id, title, amount) ->
            val expense = createExpense(id, title, amount)
            when (val addRes = addExpense(items, expense)) {
                is AddExpenseResult.Ok -> "Added: ${addRes.added}"
                is AddExpenseResult.Error -> "ERROR: ${addRes.message}"
            }
        },
        onFailure = { "ERROR: bad arguments (${it::class.simpleName})" }
    )
}

There’s a lot going on here even though the code is short: we don’t use null as a “universal answer”. Each layer speaks its own language:

  • the parser says “success/exception” (Result);
  • the domain factory says “either we create correctly, or it’s a bug/contract violation” (require);
  • the repository says “success or a business-rule error” (sealed Ok/Error).

And, importantly, the calling code doesn’t guess. It just handles the variants.

6. Common mistakes

Mistake #1: using requireNotNull as “user input validation”.
When a user enters something wrong, it’s a normal real-life situation, not a reason to crash with IllegalArgumentException. Preconditions belong where bad data means a bug or incorrect use of a function, not “the user typed the wrong digit”. For input, prefer Result or a sealed Error.

Mistake #2: making a sealed result, but hiding meaning back inside null.
A classic: sealed class Result { data class Ok(val value: T?) ... }. On paper you “moved away from null”, but in reality you just repackaged null into a box labeled “Ok”. If you have Ok, it should contain a full-fledged value. If the value may be absent, that’s a separate variant (Missing, NotFound).

Mistake #3: returning null, but printing the reason via println inside the function.
Such code is hard to test, hard to reuse, and impossible to handle properly at the UI/CLI level. A function should either return a clear result with a cause (error text/type), or crash (if it’s a precondition), but not “whisper to the console and vanish into the fog”.

Mistake #4: turning Result into an “error suppressor”.
runCatching is easy to use like a rug to sweep everything under. If you do runCatching { ... }.getOrNull() and silently ignore Failure, you come back to null, only now you’ve also lost the cause. If you chose Result, respect it: handle onFailure, add context, and form messages.

Mistake #5: mixing styles without an agreement and getting “three levels of uncertainty”.
For example, a function returns Result<User?>, where null means “not found”, Failure means “error”, and inside User there is name: String? “just in case”. As a result, you end up checking everything three times. Usually it’s better to build one clear model: either sealed Found/Missing, or Result<User>, and inside the domain model — strict non-null fields.

1
Task
Kotlin SELF, level 41, lesson 1
Locked
Cashier discount
Cashier discount
1
Task
Kotlin SELF, level 41, lesson 1
Locked
Login from input
Login from input
1
Task
Kotlin SELF, level 41, lesson 1
Locked
Product search
Product search
1
Task
Kotlin SELF, level 41, lesson 1
Locked
Parser using Result
Parser using Result
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION