CodeGym /Courses /Kotlin SELF /Nullable in sorting: defaults, splitting, and a clear rul...

Nullable in sorting: defaults, splitting, and a clear rule for null

Kotlin SELF
Level 23, Lesson 3
Available

1. Introduction

When you first encounter null in data, it may feel like: “Well, null is null, I know how to write ?:.” But sorting is not just “handle each element individually.” Sorting requires comparing elements in pairs, which means you need an answer to the question: if one element is null and the other is not null, which one is “greater” and which one is “less”? Semantically, null has no natural place in an ordering, so the decision is always a bit “political”: you agree on where null should end up—at the beginning or at the end.

In Kotlin, sorting is built around the idea of comparability and comparators: either natural order (Comparable) or custom order via Comparator (including the handy compareBy). If your sort key can be null, you must make the rule explicit. Yes, sometimes the standard library can “somehow” compare nullable keys, but the problem is not only the compiler—the problem is readability. A week later, you won’t remember why null ended up at the beginning of the list rather than at the end.

Let’s tie this to our practical console app (let’s call it BudgetBuddy): we store expenses as pairs "category" to amount. And let’s imagine that sometimes the amount is unknown (null)—for example, you decided to allow “draft” expenses: the category is entered, and the amount comes later.

2. Data model: expenses with an unknown amount

When we talk about null, it’s important not to turn it into abstract philosophy. Let null mean something concrete. In our app, we’ll treat null as an unknown amount. It’s not “zero”; it’s “no data.” And that distinction matters: zero is a number, while null is the absence of a number.

Here’s a small sample dataset that’s convenient to practice on:

fun main() {
    val expenses: List<Pair<String, Int?>> = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90,
        "food" to null
    )

    println(expenses)
    // [(food, 250), (taxi, null), (books, 90), (food, null)]
}

Here you can see that null shows up not as something exotic, but as an ordinary member of the collection. By definition, Kotlin’s nullable types force us to explicitly acknowledge that a value may be missing—and that’s good: the language literally doesn’t let you “forget” about the hole in the data.

Now imagine we want to build a report: output categories sorted by amount (for example, to later take top‑N). But some amounts are null. Where do we put them?

3. Strategy 1: a default via ?:

The most popular approach among beginners is: “let’s substitute something for null and move on.” This is indeed a working strategy—if you choose the replacement carefully. The Elvis operator ?: is made for exactly this: “if the left side is null, take the right side.”

null at the end when sorting ascending

If we sort ascending and want unknown values to go to the end, the logic is simple: when the value is null, substitute a very large number so it ends up “last.”

fun main() {
    val totals: List<Pair<String, Int?>> = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90
    )

    val sorted = totals.sortedBy { (_, total) ->
        total ?: Int.MAX_VALUE
    }

    println(sorted)
    // [(books, 90), (food, 250), (taxi, null)]
}

The idea is readable even to someone who doesn’t know Kotlin: “if there’s no amount, treat it as infinitely large so it flies to the end.”

The trick is simple, but there’s a nuance: you must not pick the default “at random.” If you put 0, null will end up at the beginning, and it will look like “taxi = 0,” while we actually wanted “taxi = unknown.”

null at the beginning when sorting ascending

Sometimes, semantically, you want the opposite: see all the “holes” at the top so the report starts with problematic data. Then for null, substitute a very small number.

fun main() {
    val totals: List<Pair<String, Int?>> = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90
    )

    val sorted = totals.sortedBy { (_, total) ->
        total ?: Int.MIN_VALUE
    }

    println(sorted)
    // [(taxi, null), (books, 90), (food, 250)]
}

This is a different agreement: “null is the smallest.” From the algorithm’s perspective, that’s perfectly valid. From a business perspective, it’s also fine if that’s the rule you choose.

sortedByDescending and the “reversed” default

This is where beginners often stumble: with sortedByDescending, everything flips. If you want null at the end when sorting descending, then null must become very small; otherwise it will suddenly end up at the beginning as the “largest.”

fun main() {
    val totals: List<Pair<String, Int?>> = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90
    )

    val sorted = totals.sortedByDescending { (_, total) ->
        total ?: Int.MIN_VALUE
    }

    println(sorted)
    // [(food, 250), (books, 90), (taxi, null)]
}

If, semantically, your amounts can’t be negative, you can choose an even more “speaking” default, for example -1, to explicitly underline: “invalid/unknown.”

4. When ?: becomes dangerous

The “substitute a number” strategy looks like a universal key, but it has a hidden cost. When you substitute a default, you effectively embed a business decision into arithmetic: you turn “no data” into “some number.” Yes, you do it only for sorting, but the next reader of the code may not understand that it’s a “technical hack,” not real business logic.

Imagine you substituted Int.MAX_VALUE, and then someone decided to compute an “average” over those keys (or do one more pipeline step) and accidentally used the already “filled in” numbers. Suddenly, the report will show a category with an amount of 2147483647, and it will look like a serious financial problem, while in reality it’s a programmer problem.

So the rule is: the ?: strategy is good when you use it only as a sort key (inside sortedBy({ … })), while keeping the original data (null) as-is. In other words, we’re not rewriting the data; we’re only choosing how to compare it.

5. Strategy 2: separate null and non-null

The second strategy is usually longer, but it wins on readability. Instead of “pretending that null is a number,” we say honestly: “first sort the known values, then append the unknown ones where we agreed.”

This approach is especially good when null means “unknown,” and you don’t want anyone to even theoretically mistake it for “0” or “infinity.”

Let’s start with a simple case: a list of numbers List<Int?>.

fun main() {
    val xs: List<Int?> = listOf(3, null, 1, null, 2)

    val sortedNotNull = xs.filterNotNull().sorted()
    val nullCount = xs.count { it == null }

    val result = mutableListOf<Int?>()
    for (v in sortedNotNull) result.add(v)
    repeat(nullCount) { result.add(null) }

    println(result)
    // [1, 2, 3, null, null]
}

The code is more verbose here, but it’s as straightforward as it gets. We used filterNotNull() and count { … }, which you’ve already seen in collection operations: first we “cleaned” the data, then counted how many items we threw away, and finally put null back, but now at the end of the list. And yes, this technique clearly highlights that null didn’t get lost—it was temporarily moved into a “separate pocket.”

6. Choosing a strategy and a readable rule for null

Sorting pairs while preserving the category

Real reports rarely sort “just numbers.” Usually we have a “name–value” pair, and it’s important not to lose the name. So let’s apply the splitting strategy to List<Pair<String, Int?>>.

The idea “split into two collections” works well here: one with known amounts and another with unknown ones. Kotlin has partition, but even without it you can write a transparent loop (and loops are usually clearer to beginners than “magic” functions).

fun main() {
    val totals: List<Pair<String, Int?>> = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90
    )

    val known = mutableListOf<Pair<String, Int>>()
    val unknown = mutableListOf<Pair<String, Int?>>()

    for ((cat, total) in totals) {
        if (total == null) unknown.add(cat to null) else known.add(cat to total)
    }

    val knownSorted = known.sortedBy { it.second }
    val result = knownSorted.map { it.first to it.second } + unknown

    println(result)
    // [(books, 90), (food, 250), (taxi, null)]
}

Notice the trick: in known we store already non-null amounts (Int), so sorting by it.second becomes “normal,” without ?:. This reduces the risk of accidentally treating null as a number and makes the rest of the logic simpler.

A mini guideline: when ?:, and when splitting

When you have a choice between two approaches, it’s easy to go to extremes. Some people start writing ?: Int.MAX_VALUE everywhere and feel like wizards. Others, on the contrary, split data into five lists everywhere and feel like accounting. To avoid overdoing it, it helps to have a simple criterion: how dangerous it is to “swap the meaning,” and how important readability is.

Below is a small guideline. It’s not a law, but it helps you decide without long meditation.

Situation ?: (default) Separation (split + merge)
Data is small, rule is simple (“null to the end”) Usually great Also OK, but can be verbose
The default is easy to choose so that it is definitely outside the domain Great Not necessary
There is a risk that the default will overlap with real values Dangerous and non-obvious More reliable
You’re afraid someone will “reuse” the default as a real number Better not More reliable
You need to explicitly keep/show null as a data issue May hide meaning Highlights meaning

And if you want a very short rule: if you can explain at a glance why the default is safe, use ?:. If you start saying things like “well, in general our amounts are almost always positive, except…”, it’s better to split.

“Ready-made rules”: null first/last as an idea

Sometimes you’ll see code where null is placed “at the beginning/at the end” using ready-made comparators or special comparison functions. Today we won’t dive into the “zoo” of comparators (so the topic of the day doesn’t bloat), but it’s important not to be scared: it’s the same idea, just packaged as a library tool.

In any case, the core idea doesn’t change: sorting is a contract, and for null you need to choose an explicit position. Kotlin, in general, likes it when intent is readable from the code: like with nullable types, where T? literally says “the value may be missing.” And for sorting, Kotlin provides tools like sortedWith(compareBy{ … }), so the comparison rule is explicit rather than hidden in a mysterious if.

7. Integrating into the app: a category report

Now we’ll write a small piece of “what this looks like in real application code,” without complicating the architecture. Let’s say we have a function that builds “totals by category,” but if at least one expense in the category is unknown (null), then the total is also unknown (because we can’t honestly compute the sum).

fun totalsByCategory(expenses: List<Pair<String, Int?>>): List<Pair<String, Int?>> {
    val categories = expenses.map { it.first }.distinct()
    val result = mutableListOf<Pair<String, Int?>>()

    for (cat in categories) {
        var total = 0
        var hasUnknown = false

        for ((c, amount) in expenses) {
            if (c != cat) continue
            if (amount == null) hasUnknown = true else total += amount
        }

        result.add(cat to if (hasUnknown) null else total)
    }

    return result
}

Now apply sorting so that null is at the end, and known totals go in descending order (a typical “top categories,” just without take(n)—you did that in the previous lecture).

fun main() {
    val expenses = listOf(
        "food" to 250,
        "taxi" to null,
        "books" to 90,
        "food" to null
    )

    val totals = totalsByCategory(expenses)

    val sorted = totals.sortedByDescending { (_, total) ->
        total ?: Int.MIN_VALUE
    }

    println(sorted)
    // [(books, 90), (food, null), (taxi, null)]
}

Notice: food and taxi are both null, so their relative order is not as important to us (it may depend on the original order). The main thing is that they are both honestly at the end. And books, with a known total, is up front.

And yes, if Int.MIN_VALUE feels like a “magic number,” that’s a normal reaction. In that case, it’s exactly where you should prefer the splitting strategy: it’s longer, but there’s less magic.

8. Common mistakes

Mistake #1: substituting a default “for convenience” without thinking about the meaning of the data.
The most common version is total ?: 0. This is almost always untrue: 0 means “exactly zero,” while null means “unknown.” After such a substitution, the report becomes logically incorrect: categories with unknown totals suddenly look “smallest,” and you end up feeding yourself the wrong conclusions.

Mistake #2: mixing up defaults for sortedBy and sortedByDescending.
In descending sorting, many people automatically do ?: Int.MAX_VALUE “so it ends up at the end,” but they get null at the beginning, because “maximum” in descending is the leader. A good way not to mess this up is to say it out loud: “I want null to be worse than everyone; therefore, in descending it must become the smallest.”

Mistake #3: accidentally losing null when it matters.
filterNotNull() is great, but it literally means “throw away all null.” If null is important as a marker of a data issue, then after filterNotNull() you won’t be able to tell the user “you have 2 entries without an amount.” In such cases, either count null separately (count { it == null }), or use splitting instead of full removal.

Mistake #4: making the sort key too “smart,” so it becomes unreadable.
Sometimes you’ll see a lambda in sortedWith or sortedBy that normalizes, validates, calls trim(), handles null, and also adds something “to make it prettier.” As a result, sorting turns into a mini-program inside the program. If the rule doesn’t fit into one understandable line, it’s better to extract it into a small function with a descriptive name—then sorting becomes readable again.

Mistake #5: using “magic numbers” without a comment and without a connection to the domain.
Int.MIN_VALUE and Int.MAX_VALUE work technically, but to a beginner they look like a spell. If you do choose the ?: strategy, try either to pick a domain default (for example, -1 if amounts can’t be negative), or at least leave a short comment explaining why this value is safe.

1
Task
Kotlin SELF, level 23, lesson 3
Locked
Sensors with missing readings
Sensors with missing readings
1
Task
Kotlin SELF, level 23, lesson 3
Locked
Draft prices
Draft prices
1
Task
Kotlin SELF, level 23, lesson 3
Locked
Ratings with nulls
Ratings with nulls
1
Task
Kotlin SELF, level 23, lesson 3
Locked
List with null
List with null
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION