1. null in collections is like sand in bearings
Collections and pipelines (chains of map/filter/...) are usually written for readability: “take a list → clean it → transform it → get the result”. But if there is a null sitting inside the collection, then at almost every step you get ?., ?:, or even the magical !!, which turns the code into a quest: “guess where it crashes”. Kotlin forces us to be honest: a nullable type is a signal that you must make a decision further down the line.
Imagine we continue our educational console project (let’s call it ExpenseTracker): it stores expenses and builds reports. And then we decide to process a “raw import” of lines (for example, the lines came from an external source or from command history).
Let the line format be amount;category;note, for example 120;food;pizza.
data class Expense(val amount: Int, val category: String, val note: String)
fun main() {
val rawLines = listOf(
"120;food;pizza",
" ;transport;metro",
"100; ;coffee",
"oops;fun;bug"
)
println(rawLines.size) // 4
}
The problem: in real life, some lines are “broken”. We can try to carry them forward as Expense?, but then almost every next operation will be forced to remember the ?.
2. Two “bad smells”: List<T?> and a nullable pipeline
When List<T?> or Map<K, V?> appears in code, it is not always a mistake. Sometimes it’s a normal intermediate form. But more often it’s a sign that you mixed two things: handling dirty input and meaningful work with data. In other words, you wanted to compute totals by category, but instead you end up discussing philosophy: “what does null in the third list element mean?”.
In Kotlin it is especially important to notice exactly where the null appeared.
List<T?> usually appears when you do map { ... } and sometimes return null inside. Kotlin supports the idea that if a transformation can return null, then further down you either have to live with it or explicitly remove it. There are dedicated tools for that — we’ll get to them now.
Mini illustration of “how it all starts”:
fun parseAmountOrNull(text: String): Int? =
text.trim().toIntOrNull()
fun main() {
val rawAmounts = listOf("10", " ", "oops", "25")
val parsed: List<Int?> = rawAmounts.map { parseAmountOrNull(it) }
println(parsed) // [10, null, null, 25]
}
The list has already become a List<Int?>. And if you now want to do sum(), you can’t — and that’s correct: “sum of what?” (of something and null?) — mathematics starts nervously smoking on the sidelines.
3. filterNotNull(): remove null and get a normal type back
When you know for sure that null in a collection means “doesn’t fit / failed / skip”, the simplest strategy is to remove null as early as possible. For that there is filterNotNull(): after it, the collection type changes from List<T?> to List<T>, and you can use normal operations again without ?. at every step.
This is a good place for discipline: “one function cleans, then we work with clean data”. Then null doesn’t spread across the project like water across a keyboard after a cup of tea (which definitely was standing “in a safe place”).
fun main() {
val parsed: List<Int?> = listOf(10, null, null, 25)
val clean: List<Int> = parsed.filterNotNull()
println(clean) // [10, 25]
println(clean.sum()) // 35
}
It’s important to feel the difference here: filterNotNull() is not just a “filter”, it is also a type change. That’s one reason it’s more convenient than filter { it != null } in “manual style”: Kotlin understands the intention and returns a non-null collection (in types).
4. mapNotNull(): transform and drop the bad items in one step
Sometimes filterNotNull() is a second step, and you want a single swing: “try to parse → if it fails, drop it”. For that there is mapNotNull { ... }. It is literally made for the scenario: “regular map, but if the transformation returned null, the element does not get into the result”.
Let’s get back to our expense import. We want to get a List<Expense> from a List<String>, skipping bad lines.
Let’s make small parser functions. They return T?, and that’s fine: we are at the “raw input” boundary.
fun parseNonEmptyOrNull(raw: String): String? =
raw.trim().takeIf { it.isNotEmpty() }
fun parseIntOrNull(raw: String): Int? =
raw.trim().toIntOrNull()
Now the full line parser:
fun parseExpenseLineOrNull(line: String): Expense? {
val parts = line.split(";")
if (parts.size != 3) return null
val amount = parseIntOrNull(parts[0]) ?: return null
val category = parseNonEmptyOrNull(parts[1]) ?: return null
val note = parts[2].trim() // note can even be empty, but not null
return Expense(amount = amount, category = category, note = note)
}
And the main thing: mapNotNull.
fun main() {
val rawLines = listOf(
"120;food;pizza",
" ;transport;metro",
"100; ;coffee",
"oops;fun;bug"
)
val expenses: List<Expense> = rawLines.mapNotNull { parseExpenseLineOrNull(it) }
println(expenses.size) // 1
println(expenses[0]) // Expense(amount=120, category=food, note=pizza)
}
We got exactly what we wanted: null was “inside” parsing, but it didn’t leak into the domain collection. The pipeline became readable again: rawLines.mapNotNull(::parseExpenseLineOrNull) is almost like a declaration of intent.
5. The “gate” pattern: clean input, then work with List<T>
Beginners often have the temptation: “let it be List<Expense?>, I’ll deal with it later”. This works exactly until the first report, where you suddenly write it?.amount ?: 0, then again, then again, and now you’ve accidentally computed a sum where input errors turned into zeros. And zero is not an “error”; it is a perfectly valid number that quietly breaks statistics.
A rule that saves your sanity: make one explicit normalization/parsing stage, and then work only with clean types.
You can picture it schematically like this:
flowchart TD
A["Raw lines (List⟨String⟩)"] --> B["Normalization (trim, split)"]
B --> C["Parsing (T?)"]
C --> D["mapNotNull / filterNotNull"]
D --> E["Clean data (List⟨T⟩)"]
E --> F["Reports / sorting / grouping"]
Now let’s add a small practical “step” to our project: build a report of category totals. We already have List<Expense>.
fun totalByCategory(expenses: List<Expense>): Map<String, Int> {
return expenses
.groupBy { it.category }
.mapValues { (_, items) -> items.sumOf { it.amount } }
}
fun main() {
val expenses = listOf(
Expense(120, "food", "pizza"),
Expense(80, "transport", "metro"),
Expense(30, "food", "coffee")
)
println(totalByCategory(expenses)) // {food=150, transport=80}
}
The key point: there is not a single ? here. And it’s not magic — it’s the “gate” discipline: once we turned raw material into Expense, and from then on we live like adults (sometimes it hurts, but it works).
6. Searching in collections: T? and how not to smear ?. everywhere
When you search for an element in a collection (find, firstOrNull, getOrNull), Kotlin honestly says: “it might not be found” — here’s a T?. That’s normal: absence of a result is a real scenario.
And here is the typical mistake: you found an Expense?, then you start passing it around as nullable, and three functions later you suddenly have Expense? in the very center of the program.
Instead, it’s usually better to do one of two things: either handle absence next to the search, or turn absence into a meaningful value (via ?:, Result, sealed, or an early return — the choice depends on the contract).
Example: find the first expense by category.
fun findFirstByCategory(expenses: List<Expense>, category: String): Expense? =
expenses.find { it.category == category }
fun main() {
val expenses = listOf(Expense(120, "food", "pizza"))
val found = findFirstByCategory(expenses, "transport")
println(found) // null
}
And now “don’t smear null”: handle it nearby.
fun printFirstExpenseNote(expenses: List<Expense>, category: String) {
val expense = expenses.find { it.category == category } ?: run {
println("Nothing found for category='$category'") // Nothing found for category='transport'
return
}
println("Note: ${expense.note}") // (won't run if nothing was found)
}
Notice that we built a “gate” again: expense after Elvis (?:) becomes non-null, and then the code is simpler.
By the way, if you work with indices, getOrNull() and similar safe operations also return nullable, and that’s expected: “the element may be absent”.
7. Map<K, V?> in reports: how to get Map<K, V> without !!
Dictionaries (Map) are a place where nullable appears “naturally”: map[key] returns V?, because the key may be missing. And here it’s easy to accidentally end up with a Map<String, Int?> in computations if you start encoding “no data” as null.
Consider an example: we want to compute the average expense per category, but if the category is empty — we get null (average is undefined). This is exactly the case where null can be a meaningful intermediate value.
fun avgByCategoryOrNull(expenses: List<Expense>): Map<String, Int?> {
return expenses
.groupBy { it.category }
.mapValues { (_, items) ->
if (items.isEmpty()) null else items.sumOf { it.amount } / items.size
}
}
Yes, items.isEmpty() after groupBy usually won’t happen (a group won’t be empty), but suppose the logic is more complex — the idea matters more to us.
Now the question: how do we get a report where we show only categories with a defined average, and we want Map<String, Int>?
The “bad but popular” variant:
// Don't do this without absolute certainty:
val clean = avgMap.filterValues { it != null }.mapValues { it.value!! }
Here !! is dangerous: you manually promise the compiler that there won’t be null. It’s better to do it “honestly” via mapNotNull over entries:
fun onlyDefinedAvgs(avgMap: Map<String, Int?>): Map<String, Int> {
return avgMap
.entries
.mapNotNull { (category, avgOrNull) ->
avgOrNull?.let { avg -> category to avg }
}
.toMap()
}
The idea is simple: we turn a Map into a list of pairs, where pairs are created only if the value is not null, and then we assemble it back into a Map. Yes, a few more characters — but zero risk of “crashing unexpectedly” and zero hidden promises.
It’s also nice that mapNotNull here again expresses the intent: “transform, but if null — drop it”.
8. Helpful nuances for pipelines
takeIf / takeUnless: control null in one place
Sometimes null is needed as an intermediate signal: for example, “the string is empty after normalization — that means there is no value”. You can use a separate if for this, but in pipelines you often want something more compact. That’s what takeIf and takeUnless help with: they return the value if the condition is true (or false), otherwise they return null.
This sounds like “we create null ourselves”, and yes — but that’s the whole point: we create it in one clear place, where it means exactly one thing.
Example: normalize a note. If after trim() it’s empty, we consider that there is no note, and we want to drop it from the list of notes.
fun normalizeNoteOrNull(raw: String): String? =
raw.trim().takeIf { it.isNotEmpty() }
fun main() {
val notes = listOf(" pizza ", " ", "coffee", "")
val cleanNotes = notes.mapNotNull { normalizeNoteOrNull(it) }
println(cleanNotes) // [pizza, coffee]
}
Here takeIf is a small, neat “null generator by rules”, and mapNotNull is a “vacuum cleaner” that immediately removed that null from the result. As a result, what leaves the pipeline is a List<String>, without nullable.
Mini report: top categories without nullable in the middle of the pipeline
Now let’s make a piece that looks like real code in our ExpenseTracker: we build the top categories by total, but we want to ignore import lines that didn’t parse. Important: we do not want List<Expense?>, and we do not want Map<String, Int?> at the end.
Let’s assemble everything in one place: “raw input → mapNotNull(parse) → report”.
fun topCategories(rawLines: List<String>, topN: Int): List<Pair<String, Int>> {
val expenses = rawLines.mapNotNull { parseExpenseLineOrNull(it) }
return expenses
.groupBy { it.category }
.mapValues { (_, items) -> items.sumOf { it.amount } }
.entries
.sortedByDescending { it.value }
.take(topN)
.map { it.key to it.value }
}
fun main() {
val rawLines = listOf(
"120;food;pizza",
"80;transport;metro",
"oops;food;bug",
"30;food;coffee"
)
val top = topCategories(rawLines, topN = 2)
println(top) // [(food, 150), (transport, 80)]
}
Notice a nice thing: null lived only inside parseExpenseLineOrNull, and in the “business part” of the report it doesn’t exist at all. That is the practical goal of this lecture: null should live where it is explainable, and die where it gets in the way.
9. Common mistakes when removing null from collections and pipelines
Mistake #1: leave List<T?> “for later”, and then write it?.x ?: 0 in every report.
Such code looks like you care about safety, but in practice you silently start “fixing” data by turning errors into zeros, empty strings, or other default values. This breaks report semantics: you no longer distinguish “no data” from “data equals zero”. It’s better to make one cleaning gate (mapNotNull/filterNotNull) and then work with List<T>.
Mistake #2: use !! after a filter because “I checked it”.
The scenario is usually this: you added a filter, then later slightly changed the condition, added another branch — and !! suddenly became a crash point. Even if it’s “obvious” right now, in a week it won’t be obvious even to you. If you filter null, do it in a way that makes the type non-null, or use ?.let { ... } rather than a promise via !!.
Mistake #3: build a pipeline that creates new nullable values at every step.
For example, map { ...? } → map { it?.something } → filter { it != null } → map { it!! }. This turns into a “ladder of crutches”. Usually you either do mapNotNull right away, or split it into two readable steps: val clean = ...filterNotNull() and then val transformed = clean.map { ... }.
Mistake #4: mix “not found” and “error” into the same null.
In pipelines this is especially insidious: one null means “line is empty”, another means “number failed to parse”, a third means “category wasn’t found”, and all of that ends up as just null. Then you do filterNotNull() and lose information about why the element disappeared. For reports this is fine, but for diagnostics and UX it often isn’t. If the reason matters, it’s better to return Result/sealed and only then decide what to drop.
Mistake #5: remove null too late — after groupings and calculations.
If null gets inside groupBy, mapValues, complex sorts, and top-N logic, you are forced to add checks in the middle of the pipeline, where they are harder to read. Most of the time it’s better to clean earlier: “get List<T> as early as possible”, and only then group and aggregate.
GO TO FULL VERSION