CodeGym /Courses /Kotlin SELF /Readable operation chains: results without mutating the o...

Readable operation chains: results without mutating the original collection

Kotlin SELF
Level 22, Lesson 4
Available

1. Why write chains instead of loops

If you have ever written code like “create an empty list → loop → add inside if → then loop again”, you already know the feeling that gradually appears: the program is like a pot of soup—we keep stirring something and fear spilling it. Call chains in Kotlin let you describe data processing as a sequence of steps, where each step returns a result, and you can see the “pipeline” (pipeline) directly in the code.

The key idea of this lecture: we try not to mutate the original collection, but to build new results on top of it. That is, instead of “took the expense list and deleted everything extra from it” we do “took the expense list and got a new list—only what we need.” This makes code more predictable: you worry less that somewhere “over there” the list has already been changed, and debugging turns into ghost hunting.

A small mini-table to keep the focus:

Operation What it returns Mutates the original collection? Typical role
filter { ... }
List<T>
no “keep what fits”
map { ... }
List<R>
no “turn into something else”
find { ... }
T?
no “find the first match”
any/all
Boolean
no “quick check”
count { ... }
Int
no “how many elements match”
forEach { ... }
Unit
no “do an action at the end”

2. The skeleton of a readable operation chain

When you first start writing chains, it is tempting to make them “as short as possible”, and then proudly look at 12 calls in a row and think: “I am a functional genius.” Usually at this moment, future you from the future pulls out a sign that says “what for” and silently shows it to you. So we need a simple, repeatable skeleton that reads like a story: first prepare the data, then select, then transform, then get the final result and (if needed) print it.

Let’s lock this in as a pattern. Not as a dogma, but as a convenient reading rhythm:

flowchart TD
    A[Data source: List⟨T⟩] --> B[Normalization: map / trim / lowercase]
    B --> C[Selection: filter]
    C --> D[Transformation: map / mapNotNull]
    D --> E[Final: find / any / all / count]
    E --> F[Action: forEach / println]

The important thing here is that forEach most often comes at the very end, when you have already obtained what you want to count/prepare. forEach is “print to the screen”, “log”, “call a function with side effects”, but not “compute and return” (for that there is count, any, find, and friends).

A mini-example “one line of meaning”: clean strings, keep non-empty, turn into lengths, count how many lengths are >= 3:

fun main() {
    val raw = listOf("  a  ", "   ", "kotlin", " go ")

    val count = raw
        .map { it.trim() }
        .filter { it.isNotEmpty() }
        .map { it.length }
        .count { it >= 3 }

    println(count) // 2
}

3. Learning example: expenses and commands without mutation

So the chains do not hang in a vacuum, let’s continue the practical console project from the days about collections and commands. We are still “without OOP” (classes will come later), so we will represent an expense as a Triple:

  • first — amount,
  • second — category ("food", "taxi", "books"),
  • third — comment.

Yes, Triple is not the peak of readability, but it is an honest “bridge” until classes. And by the way, it is a great reason to write small helper functions so the code does not look like a magical ritual of expense.first all over the program.

Expense data and helper functions

Let’s make a couple of functions that improve readability (and will be useful for callable references ::):

fun normalizeCategory(raw: String): String =
    raw.trim().lowercase()

fun formatExpense(e: Triple<Int, String, String>): String =
    "${e.first} | ${e.second} | ${e.third}"

Notice the style: each function does one thing. As soon as a function starts “normalizing, validating, and printing” at the same time, it is usually a signal that you are trying to pack three different steps into one.

Long chain vs intermediate val

Almost any chain has a “break point”: before it, it reads easily; after it, your brain starts pretending it urgently needs lunch. In Kotlin, it is normal and even useful to break long chains with intermediate val with meaningful names. This is not “extra code”, but hints to the reader: “here we already have cleaned expenses”, “here we kept only the food category.”

Let’s compare approaches with an example: print all expenses in the category entered by the user, and the category must be normalized.

Option “everything in one chain” (short, but can be hard when there are more steps):

fun printByCategory(
    expenses: List<Triple<Int, String, String>>,
    rawCategory: String
) {
    expenses
        .filter { it.second == rawCategory.trim().lowercase() }
        .map(::formatExpense)
        .forEach(::println)
}

Option with intermediate val (usually reads more calmly, especially for beginners):

fun printByCategory(
    expenses: List<Triple<Int, String, String>>,
    rawCategory: String
) {
    val category = normalizeCategory(rawCategory)
    val filtered = expenses.filter { it.second == category }
    val lines = filtered.map(::formatExpense)

    lines.forEach(::println)
}

Here you can literally see: “entered category → normalized → filtered → formatted → printed.” And this is the very “step” structure we talked about.

Commands: input → normalization → result

In console applications, there is almost always a “raw input” layer: the user enters a command as a string, the string contains spaces, weird casing, and generally complete personal freedom. Chains help turn “raw input” into normal data without the code looking like spaghetti made of if and temporary variables.

Let’s make a small function: the user enters a string of numbers separated by spaces, and we want to get a list of Int, ignoring garbage. This is the classic case for mapNotNull, because toIntOrNull() returns Int?, and we want to drop null results.

fun parseInts(raw: String): List<Int> =
    raw.split(" ")
        .map { it.trim() }
        .filter { it.isNotEmpty() }
        .mapNotNull { it.toIntOrNull() }

Here it is especially important not to mix it up: filterNotNull() removes exactly null, not empty strings. Empty strings are removed with a separate filter { it.isNotEmpty() }.

Now let’s apply the idea to our project: suppose we have a "list food" command that prints expenses by category. We want to:

  • not modify expenses,
  • get a new list of strings for printing,
  • print via forEach at the end.
fun listCommand(
    expenses: List<Triple<Int, String, String>>,
    rawCategory: String
) {
    val category = normalizeCategory(rawCategory)

    expenses
        .filter { it.second == category }
        .map(::formatExpense)
        .forEach(::println)
}

Notice: not a single add, not a single remove, no mutation. The list command should be “pure” in a good way: it only shows.

4. Terminal operations: find, any, all, count

A very common beginner mistake: they do filter, get a list, and then loop again and manually count or search. That is normal at the start (you are honestly practicing loops), but now we have operations that express intention directly: “find”, “check”, “count”. When code speaks in human language, it rarely breaks accidentally.

find: find the first matching expense

In a real application you often want: “Show the first purchase over 5000” or “Find the first entry with category "taxi".” find returns T?, and this is not a whim, but honesty: the element may not exist.

fun printFirstOver(
    expenses: List<Triple<Int, String, String>>,
    threshold: Int
) {
    val found = expenses.find { it.first > threshold }

    val message = found?.let(::formatExpense) ?: "NOT_FOUND"
    println(message)
}

The style matters here: we do not do found!!. We explicitly describe the “if not found” behavior via Elvis ?:.

any and all: checks

Checks are where chains are especially nice: instead of a manual flag var ok = false we write what we actually mean.

For example, let’s check whether there is at least one expense with a suspiciously large value (say, greater than 100_000):

fun hasHugeExpense(expenses: List<Triple<Int, String, String>>): Boolean =
    expenses.any { it.first > 100_000 }

And now an all example: are all expenses non-negative. Yes, it sounds like a “sanity check”, but in user input, sanity is an infrequent guest.

fun allNonNegative(expenses: List<Triple<Int, String, String>>): Boolean =
    expenses.all { it.first >= 0 }

Separately, a reminder of an important behavior: all { ... } on an empty collection returns true (because there is no counterexample). This is fine; just remember it when interpreting results.

count: how many expenses match

If you need a number, count is usually more expressive than filter {...}.size, because it literally says: “count by condition.”

fun countInCategory(
    expenses: List<Triple<Int, String, String>>,
    rawCategory: String
): Int {
    val category = normalizeCategory(rawCategory)
    return expenses.count { it.second == category }
}

5. Compute separately, print separately

When the code is small, it is very tempting to do println right inside map or filter: “so what, it works.” It works—until you want to reuse the computation without printing, test it, or just understand why the output is duplicated. So a useful habit is: first build the result as a value (List<String>, Int, Boolean), and only then perform the action (println, forEach).

Let’s compare with a simple example.

Bad (mixed transformation and printing):

fun printBad(expenses: List<Triple<Int, String, String>>) {
    expenses.map {
        println(it) // side effect in map — the reader cries
        it.first
    }
}

Better (first get strings, then print):

fun printGood(expenses: List<Triple<Int, String, String>>) {
    val lines = expenses.map(::formatExpense)
    lines.forEach(::println)
}

forEach at the end of a chain is like putting a period at the end of a sentence. You have already computed everything, and now you simply “use” the result.

6. A mini-scenario in main

To see the style end to end, let’s assemble a small main fragment. It does not claim to be a full command parser (it existed earlier), but it shows how chains are used in a real flow: got data → made a check → printed a list → counted.

fun main() {
    val expenses = listOf(
        Triple(1200, "food", "coffee"),
        Triple(8000, "taxi", "airport"),
        Triple(300, "food", "bread")
    )

    println(hasHugeExpense(expenses)) // false
    println(allNonNegative(expenses)) // true

    listCommand(expenses, " FOOD ")
    // 1200 | food | coffee
    // 300 | food | bread

    println(countInCategory(expenses, "food")) // 2
}

Here you can clearly see the main point: the expenses list does not change; we only “take slices from it” and build results.

7. Common mistakes when building chains

Mistake No. 1: turning forEach into a “universal shovel” for everything.
Beginners often do this: inside forEach they filter, format, count, and update external variables. It works, but the code becomes hard to verify and hard to change: any edit adds another side effect. A good rule: everything that returns a value (map/filter/find/any/all/count) should happen before forEach, and forEach should remain as the final step “use the result.”

Mistake No. 2: printing inside map or filter and getting “magical” output.
map and filter read like data transformations. When println suddenly appears inside them, the reader’s expectation breaks: they think they are building a new list, but in reality they are also triggering side effects. This is especially dangerous when the chain will be reused elsewhere: printing will “suddenly” start even though you did not plan it.

Mistake No. 3: writing a chain with 12 calls and being proud it is “in one line.”
Compactness is not the same as readability. If a chain is long, split it with intermediate val with normal names. You will not lose code quality—on the contrary, you will make it friendly to your future self who opens the project a week later and does not have to remember what exactly it was doing at step six.

Mistake No. 4: forgetting where null appears, and trying to use the result as non-null.
find returns T?, toIntOrNull() returns Int?, and this is not a “hindrance”, but a signal: the “not found / not parsed” scenario is possible. If you ignore this and reach for !!, you are not “simplifying code”—you are postponing the crash until the moment the user enters something unexpected. Most often it is better to apply ?: or clean the data up front with mapNotNull.

Mistake No. 5: confusing filterNotNull() with filtering empty strings.
filterNotNull() drops only null elements and also improves the result type to non-null, which is very convenient. But an empty string "" is not null, and it will not go anywhere. So for strings you usually need a duo: first map { it.trim() }, then filter { it.isNotEmpty() }, and filterNotNull() is applicable only if you actually have List<String?>.

1
Task
Kotlin SELF, level 22, lesson 4
Locked
Clean words
Clean words
1
Task
Kotlin SELF, level 22, lesson 4
Locked
Even Numbers from Junk
Even Numbers from Junk
1
Task
Kotlin SELF, level 22, lesson 4
Locked
Purchase within Budget
Purchase within Budget
1
Task
Kotlin SELF, level 22, lesson 4
Locked
Email validation
Email validation
1
Survey/quiz
Collection operations, level 22, lesson 4
Unavailable
Collection operations
Collection operations
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION