CodeGym /Courses /Kotlin SELF /Decomposing Text Analyzer: steps and assembling via let(:...

Decomposing Text Analyzer: steps and assembling via let(::...)

Kotlin SELF
Level 28, Lesson 3
Available

1. A pipeline as an assembly line and step types

When you first put together a pipeline, you get that pleasant feeling: “Look, mom, I’m a functional programmer.” But then two days pass, you open your code—and you catch the effect of “I didn’t write this; my night doppelganger did.” The problem is not the pipeline; the problem is that it’s hard for the brain to hold both the meaning of each step and the data type at each step at the same time.

Imagine you have a chain of 10 operations: trim, lowercase, replace, split, filter, groupingBy, eachCount, entries, sortedByDescending, take. You can write all of this in one line, but one mistake turns debugging into the game “guess where we lost the meaning.” So we do what grown-up developers do: we extract steps into separate functions with descriptive names.

When we say “decomposition,” it’s not just “split into functions because that’s what people do.” We want an assembly line where each machine has a clear input and a clear output. Then you can assemble the line in any order, test it in parts, and swap one machine without dismantling the whole factory.

To make it easier for the brain, it helps to lock in the result types at each step. Here’s what our text analyzer “assembly line” looks like:

Step Step name Input Output Meaning
1
normalizeText
String
String
Bring the text to a “neat” form
2
tokenize
String
List<String>
Split the string into words
3
countTokens
List<String>
Map<String, Int>
Count frequencies
4
topN
Map<String, Int>
List<Pair<String, Int>>
Take the most frequent items
5
formatTop
List<Pair<String, Int>>
String
Produce the report text

If you noticed, almost everything fits together perfectly here: the output of one step is the input of the next one. This is exactly the case where let(::...) becomes especially readable, because let means “pass the result along” and returns the block result. This idea maps well to the idiom value?.let { ... } and to “transforming a value via a block” in Kotlin.

Function responsibility boundaries

It’s very tempting to make a single function analyzeText() and stuff everything into it: normalization, counting, formatting, and printing to the console. But then you end up with a “combine harvester” that’s hard to reuse: for example, you’ll want to output top-N not as text but as a table—and you’ll have to rewrite half of it.

A good responsibility boundary sounds boring but works great: a function does one clear thing and returns the result without printing it and without reading input. Printing and input are the responsibility of main() (or a separate CLI layer), while pure computations are the pipeline functions. Then you can reuse the steps in another project, in tests, or with a different output mode.

2. Text Analyzer pipeline steps

Step 1 — normalizeText(text: String): String

Normalization is like “tidying the room before you start looking for socks.” If we immediately start doing split(" ") on raw text, we’ll get tokens like "" (empty string), "\n", or words in different cases. Normalization makes the input predictable: consistent spaces, consistent case, no “extra” edges.

A small function example (notice: 1 step — 1 meaning):

import kotlin.text.Regex

fun normalizeText(text: String): String =
    Regex("""\s+""")
        .replace(text.trim().lowercase(), " ")

Here we do three things: trim() removes spaces at the edges, lowercase() converts to one case, and Regex("""\s+""") collapses any “whitespace obstacle course” into a single space.

Step 2 — tokenize(text: String): List<String>

Tokenization is the moment when a string turns into a collection, and this is exactly where “invisible” bugs often appear: extra spaces produce empty elements, tabs behave differently, and a string of only spaces turns into a list with one empty token. Our goal is to get a list of words where each word is non-empty.

The simplest tokenization function can look like this:

fun tokenize(text: String): List<String> =
    text.split(" ")
        .filter { it.isNotBlank() }

Yes, after normalization we already have “one space,” but filter { it.isNotBlank() } is a seat belt. In programming, seat belts don’t look cool, but they save lives (your time and nerves).

Step 3 — countTokens(tokens: List<String>): Map<String, Int>

At this stage we do the thing the whole party is for: we turn a list of words into frequencies. In the past, many people wrote this manually via MutableMap, but in Kotlin there is a standard and very readable path: groupingBy { it }.eachCount().

The function becomes almost “self-documenting”:

fun countTokens(tokens: List<String>): Map<String, Int> =
    tokens.groupingBy { it }.eachCount()

Input: a list of words. Output: a map “word → how many times it occurred.” This step is convenient to keep separate: it doesn’t depend on where the words came from at all. Want to tokenize by spaces—go ahead; by commas—go ahead; extract words from JSON—go ahead; the frequencies are still counted the same way.

Step 4 — topN(freq: Map<String, Int>, n: Int): List<Pair<String, Int>>

Top-N is where it’s easy to get confused about types: you can’t “sort” a Map directly the way you sort a list, because sorting is about order, while a Map is semantically about access by key. So we work through entries: first we turn it into a list of elements, sort by value, take take, and only then choose the result form.

We intentionally return List<Pair<String, Int>>, because it’s convenient for formatting: a list of pairs is easy to convert into lines, a table—anything you want.

fun topN(freq: Map<String, Int>, n: Int): List<Pair<String, Int>> =
    freq.entries
        .sortedByDescending { it.value }
        .take(n)
        .map { it.key to it.value }

Notice the last line: map { it.key to it.value }. This turns Map.Entry<String, Int> into Pair<String, Int>. We don’t carry Entry forward because it’s an “internal” map type—for the next step we don’t need it.

Step 5 — formatTop(items: List<Pair<String, Int>>): String

Formatting is the “presentation” layer. Here we turn data into nice-looking text. And an important point: formatting should not compute, sort, or filter anything. If you suddenly start recomputing frequencies during formatting, it means the step boundaries have blurred.

Let’s make a simple format: one line—one word and its count:

fun formatTop(items: List<Pair<String, Int>>): String =
    items.joinToString(separator = "\n") { (word, count) ->
        "$word: $count"
    }

Destructuring (word, count) makes the code human-friendly. We already know destructuring from previous topics, and here it simply boosts readability.

5. Assembling the pipeline via let(::...)

Now for the best part: we have five small functions that you can read independently. All that’s left is to assemble them into a scenario so that it looks like an assembly line, not like a “tangle of variables.” let is perfect for this, because it’s precisely about transforming a value into a new value.

Let’s start simple: input text → report:

fun analyze(text: String, top: Int): String =
    text
        .let(::normalizeText)
        .let(::tokenize)
        .let(::countTokens)
        .let { freq -> topN(freq, n = top) }
        .let(::formatTop)

There is one “special” step here: topN requires two arguments, so we can’t just write .let(::topN)—we need to supply n. We solve this with a lambda that names its parameter freq so that we don’t multiply mysterious its.

Notice how linearly this reads: take the text, normalize it, tokenize it, count it, take top-N, format it. It’s a “story,” not a “technical instruction.”

6. Using it in main() and output example

Now let’s make a small main() that uses our analyzer. Important: main() handles input/output, and analyze does the computations. This way we don’t mix responsibilities.

fun main() {
    println("Enter text for analysis:")
    val text = readln()

    val report = analyze(text, top = 5)

    println("Top-5 words:")
    println(report)
}

If you run it and enter:

Kotlin kotlin is great, and Kotlin is fun

then the output will be roughly like this (after your normalization and simple space-based tokenization, punctuation may remain attached to words—that’s fine for the current version):

Top-5 words:
kotlin: 3
is: 2
great,: 1
and: 1
fun: 1

Yes, great, with a comma is not a bug; it’s the honest result of the fact that we are not doing “smart” punctuation cleanup yet. The main point is: architecturally, we are ready to improve any step independently.

7. Pipeline diagram

When you write pipelines, it’s useful to draw the “pipes” sometimes. It sounds childish, but it’s exactly how you quickly catch type errors and step “mismatches.”

flowchart TD
    A["String (raw)"] --> B["normalizeText(): String"]
    B --> C["tokenize(): List⟨String⟩"]
    C --> D["countTokens(): Map⟨String, Int⟩"]
    D --> E["topN(n): List⟨Pair⟨String, Int⟩⟩"]
    E --> F["formatTop(): String"]

If at some point you want to replace formatting with an “aligned table,” you just change the last block without touching the rest of the diagram. That’s the practical point of decomposition: changes stay local.

8. Readability: let(::step) instead of a chain of val

Beginners often fall into one of two extremes. Either they write everything as one giant chain, or they create 15 intermediate variables like text1, text2, list3, map4, and it turns into “archaeological digs”: what was list3, and how is it different from list2?

let(::normalizeText) is a compromise. We don’t lose linearity, but we do have clear step names. Also, these steps are easy to reuse elsewhere: for example, you can call tokenize(normalizeText(text)) separately and use the tokens for a different task.

And one more bonus: if the pipeline breaks, you can temporarily expand it into intermediate vals in just one place and then put it back—functions don’t care either way.

9. Diagnostics with also between steps

Sometimes you want to see what you got after each step. Putting println() inside normalizeText() is a bad idea: the function stops being pure and starts “making noise” whenever it’s used. But we can temporarily insert diagnostics into the pipeline via also, because also returns the original object and is meant for side effects.

For example:

fun analyzeDebug(text: String, top: Int): String =
    text
        .also { println("RAW: $it") }
        .let(::normalizeText)
        .also { println("NORMALIZED: $it") }
        .let(::tokenize)
        .also { println("TOKENS: $it") }
        .let(::countTokens)
        .also { println("FREQ: $it") }
        .let { freq -> topN(freq, n = top) }
        .let(::formatTop)

Yes, it’s longer—but it’s exactly a “diagnostics mode” that you can turn on/off. The main thing is: the step functions themselves remain pure and reusable.

10. Typical mistakes

Mistake #1: “A combine harvester instead of a pipeline.”
Often a student makes one function that normalizes, tokenizes, sorts, and prints. At first it seems convenient, but then any change turns into a risk of breaking everything at once. It’s much more stable to keep steps small: one step—one meaning, one input—one output.

Mistake #2: a blurry topN contract: returning an inconvenient type.
If topN returns List<Map.Entry<String, Int>>, it kind of works, but you’re carrying forward a type that is intended for the internal life of a Map. Formatting ends up with weird constructs, and the code becomes harder to read. It’s better to choose the result type to fit the next step, and for formatting it’s usually more convenient to use List<Pair<String, Int>>.

Mistake #3: “double it” and lost readability in let.
When you start writing nested let blocks and leave it everywhere, after a minute it’s unclear what exactly is stored in it right now: a string, a list, or a map. This is the case where it’s better to name the parameter explicitly: let { freq -> ... } or temporarily flatten the chain into a couple of intermediate variables with normal names.

Mistake #4: side effects inside computational steps.
Sometimes people add println() for debugging inside normalizeText() or countTokens() and then forget to remove it. As a result, the functions can’t be reused normally: they start printing something “on their own.” If you want diagnostics, it’s better to insert it via also at the pipeline assembly point rather than hide it inside the steps.

Mistake #5: trying to “glue” steps with different signatures via ::function.
let(::tokenize) works because tokenize takes exactly what the previous step returns. But topN also requires n, so trying to do .let(::topN) won’t work. That’s normal: just use a lambda .let { freq -> topN(freq, n = 5) } and don’t try to “beat the compiler with the power of thought.”

1
Task
Kotlin SELF, level 28, lesson 3
Locked
Clean Slogan
Clean Slogan
1
Task
Kotlin SELF, level 28, lesson 3
Locked
Word splitting
Word splitting
1
Task
Kotlin SELF, level 28, lesson 3
Locked
Word Counter
Word Counter
1
Task
Kotlin SELF, level 28, lesson 3
Locked
Top words
Top words
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION