CodeGym /Courses /Kotlin SELF /Scope function mistakes: result, it, and unnecessary “mag...

Scope function mistakes: result, it, and unnecessary “magic”

Kotlin SELF
Level 28, Lesson 4
Available

1. When scope functions hurt: syntactic sugar is sticky too

Kotlin scope functions (let, run, apply, also, with) give you compactness and a pleasant “flowing” style. But they have a downside: the code can look correct, compile with no complaints—and still do something other than what you expected.

Let’s break down the three most common groups of problems: losing the result (you chose a scope function that returns “the wrong thing”), confusion due to it/this in nested lambdas, and unnecessary “magic,” when a chain starts looking like a spell.

Scope functions are like spices: a pinch makes a dish better, but half the jar turns soup into an experiment on students. In Kotlin they really do simplify code, but the price is “hidden” decisions: what an expression returns, what the current result type is, which it is meant, where something was computed but the result was never used.

The problem is that the compiler usually doesn’t complain. It honestly does exactly what you wrote. It’s just that you wrote something different from what you thought. So today we’ll learn to catch three classes of mistakes: losing the result (you chose a scope function that returns “the wrong thing”), confusion due to nested it/this, and unnecessary “magic,” when the chain looks nice but reads like an incantation in an ancient JVM dialect.

2. Mistake No. 1: losing the result because of the wrong scope function

The most common and the most insidious mistake: you’re sure you’re “about to compute something and return it,” and Kotlin is like, “sure, I’ll return it… just not that, but the object everything happened on.” The culprits are apply and also, because they return the object itself, not the result of the last expression in the block. That’s great for configuring an object, but bad for computations.

So you don’t have to guess, keep this mini table in your head (we discussed it already, but now you need it like a first-aid kit):

Function Inside the block Returns
let
it
block result
run
(as in obj.run { })
this
block result
with(obj) { }
this
block result
apply
this
the object itself
also
it
the object itself

A classic: apply on StringBuilder, but you expected a String

Let’s start with an example that has wrecked the nerves of about half of humanity (the other half just hasn’t tried yet).

fun main() {
    val text = StringBuilder().apply {
        append("A")
        append("B")
    }

    println(text) // AB (in reality this will be the StringBuilder contents, but the type is StringBuilder)
}

When printed, it looks “as if everything is fine,” because StringBuilder knows how to print nicely. But then you suddenly want to do text.uppercase()—and you get a compilation error, because uppercase() exists on String, while text is a StringBuilder.

The correct approach: if you need the computation result, use run and return toString() as the last expression.

fun main() {
    val s: String = StringBuilder().run {
        append("A")
        append("B")
        toString()
    }

    println(s) // AB
}

The key idea here: run is “do a few actions in the context of the object and return whatever I say last.”

“I sorted a list in apply—why didn’t it sort?”

This is a special kind of pain, because it looks logical—and logic can betray you sometimes.

fun main() {
    val xs = listOf(3, 1, 2).apply {
        sorted() // I kind of called sorted...
    }

    println(xs) // [3, 1, 2]
}

Why? Because:

  • listOf(...) creates an immutable (read-only) list.
  • sorted() does not mutate the list; it returns a new one.
  • apply returns the original object—i.e., the original list.
  • You computed the result of sorted()… and threw it away.

If you want “take a list → get a new list,” that’s a job for let:

fun main() {
    val xs = listOf(3, 1, 2).let { it.sorted() }

    println(xs) // [1, 2, 3]
}

Here let honestly returns the block result.

“I filtered in also—why didn’t anything change?”

also is for side effects: logs, printing, diagnostics. It’s almost always bad for changing the meaning of the data in a chain.

fun main() {
    val tokens = listOf("kotlin", "", "is").also {
        it.filter { s -> s.isNotBlank() } // again, the result was thrown away
    }

    println(tokens) // [kotlin, , is]
}

The correct solution: filtering is a transformation, so use let (or just filter without any scope function).

fun main() {
    val tokens = listOf("kotlin", "", "is")
        .filter { it.isNotBlank() }

    println(tokens) // [kotlin, is]
}

And this is where also can and should be used—as diagnostics, without changing the result:

fun main() {
    val tokens = listOf("kotlin", "", "is")
        .filter { it.isNotBlank() }
        .also { println("tokens = $it") } // tokens = [kotlin, is]

    println(tokens.size) // 2
}

Where apply is actually great and why it’s not let

apply is an excellent “create and configure” tool. For example, when initializing mutable collections it makes the code compact and readable: you created a MutableMap and immediately filled it. This is exactly the scenario where “return the same object” is the right contract.

3. Mistake No. 2: it/this confusion in nested blocks

The second big problem appears when scope functions start nesting into each other. Lambdas in Kotlin are normal—we’ve long been writing map { ... }, filter { ... }, groupingBy { ... }. But when you add let { ... }, then inside it another let { ... }, and then the cherry on top—filter { ... }—you end up with three different “implicit” parameters on one screen. And they’re all named it.

At that point the brain often pretends it’s the garbage collector: “I’ll deal with it later; for now I’ll just skip it.”

Example: “double it” in a Text Analyzer pipeline

Imagine you’re writing a pipeline “fast, in one line, pretty.” Here’s what you get:

fun main() {
    val input = " Kotlin   kotlin  "
    val tokens = input.let {
        it.trim().lowercase().split(" ").filter { it.isNotBlank() }
    }

    println(tokens) // [kotlin, kotlin]
}

This code works. But it’s unpleasant: it inside let is the string, while it inside filter is already a token. That’s not obvious to the eye. Today you understand it, tomorrow you’re tired, the day after tomorrow you accidentally add one more level of nesting—and that’s it: welcome to “why doesn’t it compile?”

The solution is simple and adult: name the parameters.

fun main() {
    val input = " Kotlin   kotlin  "
    val tokens = input.let { text ->
        text.trim()
            .lowercase()
            .split(" ")
            .filter { token -> token.isNotBlank() }
    }

    println(tokens) // [kotlin, kotlin]
}

Now even if you open this code a month later, you’ll understand what’s going on.

Can you avoid nesting altogether?

Yes, and it’s often the best option. If you have a pipeline, it’s pleasant to read it “top to bottom” without little staircase indentations. In our previous lectures we arrived at exactly that “chain of steps” style, where each step is either a standard operation or a separate function.

fun main() {
    val input = " Kotlin   kotlin  "

    val tokens = input
        .trim()
        .lowercase()
        .split(" ")
        .filter { it.isNotBlank() }

    println(tokens) // [kotlin, kotlin]
}

No scope functions are needed here at all. And that’s fine! The most “professional” scope function is the one you didn’t use, because it reads better without it.

A this mistake: “which this is it right now?”

When you start actively using run/apply/with, another trap appears: this stops being “me and my function” and becomes “the current receiver object.” That’s great as long as there’s only one receiver. But if you get nested receivers (for example, you build a string in StringBuilder().apply { ... }, and inside you do something else with run), it’s easy to lose your bearings.

So the rule is very practical: if the block is small (1–3 lines), this inside apply/run reads great; if the block grows, nesting appears, or there are multiple objects—either name parameters via let { x -> ... }, or extract the piece into a separate function. Not because “you must,” but because you’re not a robot (and that’s normal, even if a bit annoying).

4. Mistake No. 3: unnecessary “magic” in chains

Scope functions are tempting: “look, I can do it without a single variable, in one chain, and I’ll even insert also for logs!” And then you open it a week later and realize it’s not a chain—it’s macrame.

Even in the official Kotlin style conventions, scope functions are mentioned as a separate topic of choice and readability: you should use them consciously, not by the “the more, the more Kotlin-ish” principle.

Symptom: a too-long block inside let/run

If inside let you suddenly have branching, several intermediate variables, println, and you yourself can’t briefly say “what this block does,” then the scope function is no longer helping—it’s hiding complexity.

Suppose you format a top-N report and cram everything into let:

fun main() {
    val freq = mapOf("kotlin" to 2, "java" to 1)

    val report = freq.let {
        val top = it.entries.sortedByDescending { e -> e.value }.take(1)
        val line = top.joinToString { e -> "${e.key}: ${e.value}" }
        "TOP:\n$line"
    }

    println(report) // TOP: kotlin: 2
}

This is still tolerable, but already borderline. When you have 3–4 such blocks in a row, the code turns into “why is there even a let here?”

A cleaner style for our Text Analyzer is to extract steps into functions and keep the chain linear. We did this in the previous lecture: the “magic” disappears because each link is a function name, not an anonymous block.

Symptom: also does important work

also semantically means “and also this.” That is, you do the main chain and in parallel perform a side effect: printing, logging, measuring time, checking. If inside also you change data or make a decision, you write code that looks like “just a log” but actually affects the result. That’s a bad deal: you save two lines, but you pay with an hour of debugging.

Here’s a bad example (important logic is hidden in also):

fun main() {
    var limit = 2

    val top = mapOf("a" to 1, "b" to 5, "c" to 3).entries
        .sortedByDescending { it.value }
        .also { limit = 1 } // suddenly change limit
        .take(limit)

    println(top.map { it.key }) // [b]
}

It works, but it reads like “who swapped the variable at night?” If you need to change limit, do it explicitly before the chain or pass it as a parameter.

A good also: diagnostics only; it doesn’t change the result.

fun main() {
    val top = mapOf("a" to 1, "b" to 5, "c" to 3).entries
        .sortedByDescending { it.value }
        .also { println("sorted keys = ${it.map { e -> e.key }}") } // sorted keys = [b, c, a]
        .take(2)

    println(top.map { it.key }) // [b, c]
}

Symptom: scope functions “just in case”

Sometimes you see a style like:

val result = input
    .let { it.trim() }
    .let { it.lowercase() }
    .let { it.split(" ") }

This isn’t an error, but it’s noise. Here let doesn’t add meaning: normal calls already read linearly. You need let when you change the call shape (for example, you want to insert a callable reference ::normalizeText), or when you work with nullable (?.let), or when you want to bind an intermediate result to a name inside the block.

Mini check: how to read a chain and catch mistakes early

Here’s the good news: most scope function mistakes can be caught if you read the code a bit slower than usual (yes, that sounds like “just be careful,” but there is a specific technique here).

When you see . and a scope function, ask yourself two questions while reading: “what is the context object inside the block?” and “what does this call return?” If you can’t answer in 2–3 seconds, the code is already on the edge of readability, and it’s better to simplify it.

Then it’s useful to look at the result type after each step. In IntelliJ IDEA it’s basically cheating: hover over the expression and the IDE will show the type. If after apply you expected a String, but the IDE shows StringBuilder, you just caught the bug before running (and that’s the best kind of debugging—when nothing has crashed yet).

And finally: if it feels like the chain has become “too clever,” try rewriting it using 2–3 intermediate val values with normal names (normalized, tokens, freq, top). If it becomes easier to read, then that’s what you should do. Scope functions should serve readability, not a “who’s shorter” contest.

5. Typical mistakes when working with scope functions

We keep the format of this section so you can quickly scan it and say: “yep, I’ve done that before, and I felt embarrassed about it”—in a good way.

Mistake No. 1: using apply/also where you need the computation result.
When you want to “get a new value” but write apply, you almost certainly lose the result: sorted(), filter(), map() inside the block will be computed, but go nowhere, because apply returns the original object. In such places you usually want let, run, or just a direct call without a scope function.

Mistake No. 2: “I did sorted()/filter() inside the block, so the collection changed.”
Many collection operations in Kotlin return a new list rather than mutating the original. If you didn’t assign the result (or return it from let/run), then you simply “thought about sorting”—and that’s it. In a Text Analyzer this is especially visible for tokens: you forgot to apply filtering, and you got empty words in the frequencies.

Mistake No. 3: nested it’s, making it unclear what is being processed.
When a single expression contains let { it ... filter { it ... } }, you force the reader to keep two different it values in their head. The compiler will cope, but a human won’t always. The cure is either explicit names (text, token, entry) or flattening the code into several steps.

Mistake No. 4: big blocks inside scope functions that hide the algorithm.
Scope functions work best as short “adapters”: 1–5 lines. When the block already contains a mini program (branching, multiple val values, multiple meanings), the code stops being a linear pipeline. In such cases it’s better to extract the block into a named function and keep only its name in the chain—this gives you readability without losing structure.

Mistake No. 5: using also for important logic and side effects that affect the result.
also should be “off to the side”: print, log, check, but not change the meaning of the data. If inside also you change variables, mutate collections, or decide how many elements to take in take(n), you create code that looks like “diagnostics” but actually changes behavior. This is an almost guaranteed source of surprises.

Mistake No. 6: trying to make code “more Kotlin,” adding let everywhere.
Sometimes scope functions start being used as decorative style: “let’s put .let { it } here.” This makes code longer and noisier. A good sign of a healthy solution: if you remove the scope function and replace it with a normal call, the code doesn’t get worse. If it gets better, the scope function was unnecessary.

1
Task
Kotlin SELF, level 28, lesson 4
Locked
Participant badge
Participant badge
1
Task
Kotlin SELF, level 28, lesson 4
Locked
Report sorting
Report sorting
1
Task
Kotlin SELF, level 28, lesson 4
Locked
Readable lambdas
Readable lambdas
1
Task
Kotlin SELF, level 28, lesson 4
Locked
Logs without side effects
Logs without side effects
1
Survey/quiz
Scope functions and Text Analyzer walkthrough, level 28, lesson 4
Unavailable
Scope functions and Text Analyzer walkthrough
Scope functions and Text Analyzer walkthrough
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION