1. Why + in a loop can become a problem
When you are just starting to program, you want to solve problems in the most straightforward way: “need to assemble text — fine, I will do text = text + piece”. That is normal: the brain saves energy and chooses the most obvious move. The problem is that strings in Kotlin (as in many languages) are immutable, and with frequent concatenation we unintentionally create a pile of temporary strings.
Imagine that a string is a sheet of paper. You cannot write into the middle of the sheet “in place”. Each time you have to take a new sheet, copy the old content onto it, and then add the new piece. With three concatenations you will not notice. With three thousand — your computer will notice (and maybe the computer next to it too, because the fans start talking to space).
Let’s look at a typical “naive” example:
fun main() {
var text = ""
for (i in 1..5) {
text += "Line $i\n"
}
print(text)
// Line 1
// Line 2
// Line 3
// Line 4
// Line 5
}
From the results perspective, everything is great. But under the hood, on each iteration a new string is created, the old one is copied into it, and then a new fragment is added. The larger the final text, the more copying happens. This is not an “error”; the compiler will not complain, the program will work — it will just do extra work.
An important practical takeaway: if you are building text in a loop, especially many lines, it is almost always worth thinking about StringBuilder.
2. StringBuilder: build text efficiently and predictably
If concatenation via + is like rewriting text onto a new sheet of paper every time, then StringBuilder is like a notebook where you keep adding pages without retyping the previous ones. It stores a mutable character buffer inside and can efficiently “grow” its contents.
In Kotlin, StringBuilder is used all the time — it is just often invisible to you. For example, the compiler can optimize some kinds of string templates. But in loops and when building complex text, it is better to take control and use StringBuilder explicitly.
The minimal “skeleton” almost always looks like this:
- create StringBuilder()
- do many append(...) / appendLine(...)
- at the end call toString() once and get the finished String
Here is a tiny example:
fun main() {
val sb = StringBuilder()
sb.append("Hello")
sb.append(", ")
sb.append("Kotlin")
println(sb.toString()) // Hello, Kotlin
}
Here you can already see an important shift in thinking style: we do not recreate the final string at each step. We accumulate pieces, and at the end we “freeze” the result.
Another nice point: many append(...) methods return the same StringBuilder, so sometimes you can write chained code (but without fanaticism — readability matters more than “prettiness”):
fun main() {
val text = StringBuilder()
.append("A")
.append(" + ")
.append("B")
.toString()
println(text) // A + B
}
Line breaks: '\\n' and appendLine()
When you are building multi-line text, the main “glue” between lines is the line break. And this is where a small everyday tragedy often begins: you forget "\n" somewhere, add two somewhere else, end up with an extra blank line at the end, and the report looks like it was formatted by a cat walking across the keyboard.
In Kotlin there are two common approaches.
The first is to manually add the newline character '\\n'. It is simple and transparent: you explicitly control every line break.
fun main() {
val sb = StringBuilder()
sb.append("First").append('\n')
sb.append("Second").append('\n')
print(sb.toString())
// First
// Second
}
The second is to use appendLine(...). This is a convenient way to “add a line and a newline”. It is important to understand that appendLine() is an extension function from the standard library for StringBuilder: it is called like a “method”, although technically it is an extension.
Example:
fun main() {
val sb = StringBuilder()
sb.appendLine("First")
sb.appendLine("Second")
print(sb.toString())
// First
// Second
}
The practical rule is this: if you are building “report lines” one by one, appendLine(...) usually makes the code cleaner. If you need finer control over characters somewhere (for example, not always adding a newline), '\\n' is sometimes clearer.
Discipline: “build → return the string”
It is very tempting (especially for beginners) to do this: “well, I am building a report, so I will println(...) each line as I go”. It seems easier. But it quickly leads to calculation logic, formatting, and console output being mixed into one big tangled ball. And as we know, you only untangle such a ball in two cases: either on an exam, or in production. Usually at the same time.
The discipline “build → return the string” means a simple style: a function formats the text and returns it, and the caller code prints it. This gives three big advantages.
- The function is easier to test: it deterministically returns a string, and you can compare it with the expected one.
- It is easier to reuse: today we print to the console, tomorrow we might want somewhere else — and the text is already ready.
- You clearly separate responsibilities: the function “builds”, main “shows”.
A small example:
fun buildGreeting(name: String): String {
val sb = StringBuilder()
sb.append("Hello, ")
sb.append(name)
sb.append('!')
return sb.toString()
}
fun main() {
val text = buildGreeting("Alice")
println(text) // Hello, Alice!
}
Note: inside buildGreeting() there is not a single println. It does one job — it assembles a string.
Line breaks without chaos: two working styles
When you are building many lines, the “extra newline” problem almost always appears. And here what matters is not so much “which way is correct”, but rather “that you pick a rule and stick to it”. Then the output will be stable, and your brain will stop guessing each time whether an empty line will appear at the end.
There are two popular styles.
First style — “a newline after every line, including the last”. It is simpler to implement and is often perfectly fine for console reports. You just do appendLine(...) on every iteration, and that is it.
fun buildList(items: List<String>): String {
val sb = StringBuilder()
for (item in items) {
sb.appendLine(item)
}
return sb.toString()
}
Second style — “a newline only between lines”. It is useful if it is important that the last line does not end with a newline (for example, sometimes this matters for string comparisons or some formats). Then we do not always add '\\n', but conditionally, usually based on the index.
fun buildListNoTrailingNewline(items: List<String>): String {
val sb = StringBuilder()
for (i in items.indices) {
sb.append(items[i])
if (i != items.lastIndex) sb.append('\n')
}
return sb.toString()
}
Both approaches work. In console utilities, the first is chosen more often because it is simpler and does not force you to think about the last element every time. But if you start using the second style — use it everywhere in the same module; otherwise reports will start behaving “one way here, another way there”.
3. Example: an expenses report using StringBuilder
Up to this point we have been learning to format strings so that they look decent. Now imagine our training console app stores expenses as a list of pairs: category and amount. We want to build a multi-line report: a header, lines with categories, and a total at the end. And here StringBuilder is exactly what you want.
Let’s start with a bit of formatting for a single line. We already know padEnd/padStart, so we will make a two-column “table”: category on the left, amount on the right.
fun formatRow(category: String, amount: Int): String {
val left = category.padEnd(12)
val right = amount.toString().padStart(6)
return left + right
}
Here + is perfectly fine: we concatenate two short strings once. The problem starts when there are hundreds of such lines and we concatenate them in a loop into one large string.
Now let’s make a function that builds the whole report and returns a single string:
fun buildExpensesReport(expenses: List<Pair<String, Int>>): String {
val sb = StringBuilder()
sb.appendLine("== EXPENSES REPORT ==")
var total = 0
for ((category, amount) in expenses) {
sb.appendLine(formatRow(category, amount))
total += amount
}
sb.appendLine("Total: $total")
return sb.toString()
}
Notice how “even” the logic is here: we iterate over the data, add lines, and add the total at the end. No “glued” println in the middle, no result += ... in a loop.
And let’s test it in main:
fun main() {
val expenses = listOf(
"food" to 1200,
"transport" to 350,
"coffee" to 250
)
val report = buildExpensesReport(expenses)
print(report)
// == EXPENSES REPORT ==
// food 1200
// transport 350
// coffee 250
// Total: 1800
}
Note a small detail: we used print(report), not println(report), because the report already contains line breaks. This is not a “mandatory rule”, but it makes it easier to control whether an extra blank line will accidentally appear at the end.
Make it a bit more complex: add a table header
As a report grows, you want to visually separate blocks. StringBuilder lets you do that very explicitly:
fun buildExpensesReportV2(expenses: List<Pair<String, Int>>): String {
val sb = StringBuilder()
sb.appendLine("== EXPENSES REPORT ==")
sb.appendLine("CATEGORY".padEnd(12) + "AMOUNT".padStart(6))
sb.appendLine("------------------")
for ((category, amount) in expenses) {
sb.appendLine(formatRow(category, amount))
}
return sb.toString()
}
You can see the main idea: a report is essentially a “text script”, and StringBuilder helps you write that script step by step.
4. When you do not need StringBuilder: joinToString() and ready-made strings
It is easy to fall in love with StringBuilder and start using it everywhere like a universal hammer. But practice is calmer: if you already have a List<String> of ready-made strings, then joinToString("\n") is often simpler and more readable. StringBuilder is more useful when lines are formed on the fly, there are conditions, blocks, headers, totals, and you want to assemble the text as a “script”.
Let’s compare the options in a small table:
| Approach | When it is good | When it is bad |
|---|---|---|
|
1–3 concatenations, short string, “quick sketch” | Loops, hundreds of lines, large texts |
|
You already have a List<String> and need to join it | You need complex branching, headers/totals, controlled blank lines |
|
Step-by-step building, loops, large reports, control over newlines | Too much “noise” for small strings |
The key idea: StringBuilder is not “speed magic”, it is a discipline tool. It literally nudges you toward the style “build the result first, then return it”, which makes code more stable and clearer.
You can even draw a small diagram of how the flow should look:
flowchart TD
A[Data: expenses] --> B[Format lines]
B --> C[StringBuilder: append / appendLine]
C --> D["Final string: toString()"]
D --> E[print/println in main]
5. Common mistakes when working with StringBuilder
Mistake #1: continuing to do result += ... in a loop “out of habit”.
Usually this happens not because of lack of knowledge, but because of automatism: your hand reaches for += because it is faster to type. As a result, the program starts creating many temporary strings. A good habit is: if you see a loop and “building text”, almost reflexively create val sb = StringBuilder().
Mistake #2: printing inside a function that is supposed to build a string.
When buildReport() does println(...) inside itself, you lose control over output: you cannot easily change where printing happens, testing is harder, reuse is harder. It is much more robust when the function returns a string and printing happens in main.
Mistake #3: getting confused with line breaks and ending up with extra blank lines.
The most common everyday version is when an “extra emptiness” suddenly appears at the end of the report because you did both appendLine() and then also println(report). Pick a rule: either the report contains line breaks itself and you do print(report), or you build without a trailing newline and print via println.
Mistake #4: mixing different building styles in one place.
If some lines are built with StringBuilder, some with joinToString, and some with + in a loop, the code quickly becomes hard to read: you keep switching mental models. It is better to choose one dominant style for a given task: “build reports with a builder”, “join a list of ready-made strings with joinToString”.
Mistake #5: forgetting to call toString() and trying to return StringBuilder.
Sometimes beginners return the StringBuilder itself from a function and then wonder why types do not match or why “it is almost a string”. StringBuilder is a container for building. The final product is a string. That is why the final string should appear in one place in almost all cases: return sb.toString().
GO TO FULL VERSION