1. Multiline strings
When you’re just starting to program, it seems like console output is simply: println("something"), and that’s it. But as soon as you want to print a menu, help text, a “nice header,” or a mini report spanning multiple lines, the circus begins. You can insert \n manually, but the code becomes hard to read, and editing the text turns into a “find where the extra slash is” game.
That’s exactly why Kotlin has multiline strings (also called raw strings): they let you write text in code almost exactly how it should look in the console, without a mess of \n. Kotlin conventions explicitly recommend using multiline strings instead of manually embedding \n, and for indentation control, using trimIndent() or trimMargin().
As a warm-up, here’s a small contrast. First we’ll do it bluntly with \n, and then we’ll do it nicely.
fun main() {
val help = "Commands:\n" +
"1) add\n" +
"2) list\n" +
"3) exit\n"
print(help)
}
Yes, it works. But editing something like that is the kind of fun that ranks right up there with “cleaning a keyboard with a toothbrush.”
Multiline string syntax """...""" and how it differs from "..."
A multiline string in Kotlin is written using triple quotes: """ ... """. It looks a bit unusual, but the logic is simple: inside such a literal you can write line breaks as-is. That is, you press Enter—and an actual newline character appears in the string. This dramatically improves readability, especially for large blocks of text: menus, report templates, “banners,” etc.
An important nuance: it’s called raw not because it’s undercooked, but because inside it you hardly need to escape anything. In particular, \n and \t inside a raw string are just two characters: \ and n (or t), not “newline” and “tab.” This is both convenient and tricky: convenient—because less escaping; tricky—because sometimes you expect one thing and get another.
Here’s a basic example of a multiline string:
fun main() {
val help = """
Commands:
1) add
2) list
3) exit
"""
print(help)
}
Notice: the text in the console will be exactly the same as in the code. That’s the main idea.
Why indentation “sticks” to the output and why you need trimIndent()
When you start writing multiline text inside a function, you almost always indent it in code—simply because it looks nice and follows formatting rules. But a raw string preserves spaces literally. This creates a classic situation: in code everything is aligned, but in the console your menu suddenly shifts to the right by four spaces, because you wrote the string inside the fun main() block.
trimIndent() solves exactly this problem: it removes the common (minimal) indent from all non-blank lines of a multiline literal. Kotlin conventions phrase it like this: “use trimIndent() when the result doesn’t need special internal indentation.”
Example: first “bad” (indentation will appear in the output), then “good.”
fun main() {
val help = """
Commands:
1) add
2) list
3) exit
"""
print(help)
}
This code will print lines with indentation. Now the same thing, but with trimIndent():
fun main() {
val help = """
Commands:
1) add
2) list
3) exit
""".trimIndent()
print(help)
}
Now the spaces that were only needed to make the source look nice don’t mess up the final text.
A simple way to remember it: trimIndent() is like “remove the code’s formatting indent, but keep relative indentation inside the text if it actually differs.”
trimMargin() — when you need more precise indentation control
Sometimes you want the text to have indentation inside (for example, you’re printing pseudo-code, an email template, or a report block), but you don’t want to drag extra left-side “junk” into the output just because of Kotlin code formatting. In such cases, trimIndent() may be not controllable enough: it removes the common indent, but doesn’t let you explicitly mark the text boundary.
That’s where trimMargin() comes in: you choose a marker character (by default it’s |) and write lines so that everything “to the left of the marker” is cut off. In Kotlin conventions, this is described as the option for cases where internal indentation is needed and important.
Example with trimMargin():
fun main() {
val report = """
|User: Ira
|Status: OK
|Message: Data accepted
""".trimMargin()
println(report)
}
Here you can align the code indentation however you want, but the “text boundary” stays stable. If you look closely at examples in Kotlin guides, it’s the same idea: | helps neatly “trim” the left part and keep the output clean.
A small bonus: trimMargin() can work not only with |. You can choose another marker (for example >), but most of the time | is the de facto standard, and it’s best not to reinvent the wheel unless you run a wheel factory.
Multiline strings and string templates: how to interpolate values
Up to this point we used string templates in regular strings: $name, ${a + b} and so on. They work the same way inside """...""". That’s convenient: you can make a multiline “report template” and insert variables without concatenation.
A quick reminder of template syntax: you can insert a simple identifier as $a, and expressions as ${...}.
Here’s a short example of “multiline report + data”:
fun main() {
val user = "Ira"
val total = 3
val text = """
|User report
|---------------------
|Name: $user
|Purchases: $total
""".trimMargin()
println(text)
}
In the previous lecture we discussed an interesting case: if you need to print a dollar sign as text, Kotlin will try to treat $ as the start of a template. In a regular string you would write "\$". This also matters in a raw string, but today we won’t dive deeper—just remember that $ is a “special character” for interpolation, and it’s not always “just a dollar sign.”
2. Simple text alignment: padStart() and padEnd()
How to make simple “columns” without turning into Excel
After you learn to print multiline text, you almost immediately want the next thing: “Can I make numbers line up in a column, like in a table?” You can. And no, we don’t need Excel, a magic formatter, or printing on a 1997 dot-matrix printer (though it has its own charm).
padEnd(width) pads a string on the right with spaces (or another character) until it reaches the desired length. padStart(width) does the same, but on the left. As a result, you can left-align names and right-align numbers, like in reports and receipts.
One important caveat: these functions work with strings. So numbers (Int) usually need to be converted to a string via toString(). You already know how to do that.
Mini alignment example:
fun main() {
val item = "Tea"
val qty = 3
val price = 90
val line = item.padEnd(10) +
qty.toString().padStart(3) +
" x " +
price.toString().padStart(4)
println(line) // Tea 3 x 90
}
Here we made a “very simple” table-like line. Yes, it’s not a full report yet, but you can already see that values don’t jump around, even if qty becomes 12, and price becomes 160.
3. Printing a receipt in a console app
Now we’ll assemble a small, cohesive piece of a program that we’ll keep developing later in the course. The idea is simple: a mini “Coffee shop in the console.” The user enters quantities (for now without complex commands and without storing years of history), and the program prints a neat receipt: header, list, and total.
Why this is a good example for this lecture: we immediately have a multiline “header” and “footer,” and we have tabular lines where padStart()/padEnd() really help.
First, a function that returns a nice header. We intentionally return a String so you can see: a multiline string is just a regular string—just written more conveniently.
fun buildHeader(): String {
return """
|========================
| Kotlin Coffee CLI
|========================
""".trimMargin()
}
Now let’s make a function for formatting a single receipt line. For now we’ll keep it as simple and “stringy” as possible, without any fancy extras.
fun formatLine(name: String, qty: Int, price: Int): String {
val sum = qty * price
return name.padEnd(12) +
qty.toString().padStart(3) +
" x " +
price.toString().padStart(4) +
" = " +
sum.toString().padStart(5)
}
Notice the style: we compute sum first, then format the line. This is almost always more readable than stuffing qty * price into the middle of a long concatenation. In the previous lecture we discussed a similar idea for string templates: complex stuff first into a val, then into the text.
Now—main, where we use the header, formatting, and a multiline prompt for input. Here we use arrays because they are a perfect fit for a “fixed set of products” at the start.
fun main() {
val names = arrayOf("Espresso", "Cappuccino", "Tea")
val prices = intArrayOf(120, 160, 90)
val qty = IntArray(names.size)
println(buildHeader())
for (i in names.indices) {
print("How many '${names[i]}'? ")
qty[i] = readln().toInt()
}
println()
println("Receipt:")
for (i in names.indices) {
println(formatLine(names[i], qty[i], prices[i]))
}
}
Let’s add the final touch: the receipt footer, also as a multiline string. And show the total sum. The total is just an Int; we compute it in a loop.
fun buildFooter(total: Int): String {
return """
|
|------------------------
|TOTAL: ${total.toString().padStart(5)} EUR.
|Thank you! Come again :)
""".trimMargin()
}
And update the end of main by adding total calculation and printing the footer:
fun main() {
val names = arrayOf("Espresso", "Cappuccino", "Tea")
val prices = intArrayOf(120, 160, 90)
val qty = IntArray(names.size)
println(buildHeader())
for (i in names.indices) {
print("How many '${names[i]}'? ")
qty[i] = readln().toInt()
}
var total = 0
println("\nReceipt:")
for (i in names.indices) {
total += qty[i] * prices[i]
println(formatLine(names[i], qty[i], prices[i]))
}
println(buildFooter(total))
}
You now have a program where the header and footer read normally in code (no need to mentally interpret \n), indentation doesn’t drift thanks to trimMargin(), and receipt lines look aligned thanks to padStart()/padEnd(). This is exactly the style that is usually recommended: multiline strings plus explicit indentation control via trimIndent()/trimMargin().
To lock in the picture, here’s a small diagram of what we did (not code, but a “thought route”):
flowchart TD
A["Write text in '''''' ...'''''' "] --> B["Remove formatting indentation with trimIndent/trimMargin"]
B --> C["Insert data via $var and ${expr}"]
C --> D["Align columns with padEnd/padStart"]
D --> E["println(...) to the console"]
4. Common mistakes when working with multiline strings
Mistake #1: expecting """...""" to automatically “align nicely.”
A raw string preserves spaces and line breaks literally. So if you wrote the text with indentation in code, it will be printed with that indentation. The fix is not “think positive,” but something concrete: trimIndent() or trimMargin()—depending on whether internal indentation is needed.
Mistake #2: writing \n inside a raw string and expecting a line break.
Inside """...""", the sequence \n does not turn into a newline; it’s just two characters. A line break is made with a real Enter. If you want to “control” line breaks, do it either with real line breaks, or use a regular string "..." (but today the point is specifically not to suffer with \n).
Mistake #3: confusing what exactly trimIndent() removes.
trimIndent() removes the common minimal indent from non-blank lines. If you want to explicitly control the boundary of each line (for example, part of the text must be “inside a block” and have its own indentation), then trimMargin() is usually clearer: you place | yourself and see where the meaningful text begins.
Mistake #4: trying to align numbers with spaces “by eye.”
When you write "Tea 3 90" by hand, it seems fine until "Cappuccino 12 160" appears. Everything immediately “floats.” padStart()/padEnd() solve the problem because the column width is defined by a number, not by the author’s mood.
Mistake #5: aligning an Int without converting it to a String.
padStart and padEnd are string operations. If you try to apply them to a number directly, the compiler will (fairly) say: “I get what you want, but Int doesn’t have that method.” The solution is simple: qty.toString().padStart(3) and similarly for other numbers.
Mistake #6: overloading one huge string with computations and formatting.
Technically you can write a 200-character monster and be happy that it’s “all in one line.” Practically, two days later you’ll be asking yourself: “who wrote this and why do they hate me?” A slightly more grown-up style is to compute values first in a val (for example, sum), and then format the string. This approach makes code more readable and reduces the risk of formatting mistakes.
GO TO FULL VERSION