The Analogy: The Telegram Counter's Two Forms
The telegram counter at a district post office keeps two pads of forms under the glass, and the clerk decides which one a customer's message goes onto. The buff pad is the coded form. On it, certain words and marks are not part of the message at all but instructions to the operator: a written STOP becomes a full stop at the far end, an underline means the following word is transmitted twice for confirmation, and the little crossed circle in the margin means start a fresh line. The white pad is the verbatim form. Whatever is written on it is photographed and sent character for character, margins and all, with nothing treated as an instruction. The buff form costs less to send because the instructions are short. The white form costs more because nothing can be abbreviated.
The buff form is Kotlin's ordinary string literal, the one written between single quotation marks, and the marks that mean something other than themselves are the escape sequences. Inside those quotes, the two characters backslash and n are not a backslash followed by a letter; they are one instruction meaning "a line break goes here". The same is true of a backslash and t for a tab, and of a bare dollar sign, which is the instruction that says "stop copying and go and fetch a value". The white form is the raw string, written between three quotation marks, where a backslash is a backslash and a line break in the source is a line break in the value.
The counter has a third habit worth borrowing. When a clerk copies a long message onto the white form, they indent it neatly under a heading so the page is legible on the desk, and then a guillotine trims the left margin off before the sheet goes into the transmitting frame, because the margin was for the clerk's benefit and not the recipient's. That trimming is trimIndent(), and it is what makes a raw string usable inside an indented function without the indentation leaking into the value. The dollar-sign fetch works on the white form too, which is why a raw string is the natural way to write a multi-line template with values dropped into it.
The failure mode is a message that contains the instructions. A customer hands in a note about a shipment held at C colon backslash TEMP, the clerk copies it faithfully onto the buff form, and the operator at the far end reads the backslash and the T as an instruction for a tab: the address arrives with a hole in it and nobody can see what was lost, because a tab looks like a space. In Kotlin that is "C:\temp", which is a perfectly legal literal containing a tab character, compiling without a murmur and failing at whatever opens the path. The counter's rule is the same as Kotlin's: if the text you are carrying contains the marks the form treats as instructions, use the other form.
Syntax or Core Structure
Three things are happening on the same page here: escapes inside an ordinary literal, values fetched into the text by a dollar sign, and a raw string that carries its own line breaks. The whitespace is deliberately made visible rather than printed, because a tab in a report looks exactly like a run of spaces and that is how alignment bugs survive review.
fun main() {
val vessel = "Aurora"
val crew = 14
println("vessel: $vessel")
println("crew next voyage: ${crew + 2}")
val escaped = "col1\tcol2\nrow1\trow2"
println("escaped shown: " + escaped.replace("\t", "[TAB]").replace("\n", "[NL]"))
println("escaped length: ${escaped.length}")
println("cost: \$40")
val raw = """
MANIFEST
vessel $vessel
crew $crew
""".trimIndent()
println(raw)
println("raw lines: ${raw.lines().size}")
}
Output:
vessel: Aurora
crew next voyage: 16
escaped shown: col1[TAB]col2[NL]row1[TAB]row2
escaped length: 19
cost: $40
MANIFEST
vessel Aurora
crew 14
raw lines: 3
The length of 19 is the arithmetic that proves the point: four characters, one tab, four, one newline, four, one tab, four. The escapes are one character each in the value even though they take two in the source, and replace had to be given the same two-character escape to find them. The literal dollar on the cost line needed a backslash of its own, because an unescaped dollar followed by a name is a fetch instruction and Kotlin would have looked for a variable called 40. In the raw string nothing is escaped and nothing needs to be: the two line breaks are real newlines typed into the source, trimIndent() removed the eight spaces that every line shared, and the blank first and last lines went with it, leaving exactly three lines.
Technical Depth: Immutability, Escapes and the Cost of Building Text
A Kotlin String is an immutable sequence of Char values, and on the JVM it is the same java.lang.String the platform has always had. Immutable means every method that appears to change a string returns a new one, which is what makes strings safe to share between threads and expensive to build in a loop.
Every escape the compiler recognises
| escape | what the value contains | note |
|---|---|---|
\n | one newline character | not a backslash and an n |
\t | one tab character | indistinguishable from spaces once printed |
\r | one carriage return | pair it with \n only when a protocol demands both |
\\ | one backslash | needed for Windows paths and regex sources |
\" | one double quote | unnecessary inside a raw string |
\' | one apostrophe | required in a Char literal, optional in a String |
\$ | one dollar sign | without it, a following name is read as a template |
\u0041 | the character at that code unit | exactly four hex digits, no braces |
There is no escape processing at all inside a raw string, which cuts both ways: it is the right container for a Windows path, a regular expression or a block of JSON, and it is the wrong container for a string that must end in a quote character, because there is no way to escape the closing delimiter. Raw strings also cannot contain a dollar sign followed by a name without it being read as a template, so a literal dollar in raw text is written as an interpolation of a one-character string.
Four ways to assemble text, and what each costs
| approach | allocations for n pieces | best for |
|---|---|---|
a + b + c in one expression | one, if all parts are constants that fold | short fixed text |
+= inside a loop | one new string per iteration, quadratic in total | nothing; this is the mistake |
buildString { } | one buffer, resized as it grows | loops and conditional pieces |
joinToString() | one buffer plus the separator handling | turning a collection into a line |
The quadratic case is worth being precise about, because it is invisible in a small test. Appending to a string with += copies the whole accumulated text each time, so a thousand appends of ten characters copy about five million characters rather than ten thousand. buildString wraps a StringBuilder, which keeps one growable array and copies only when it doubles, and it returns an ordinary immutable String at the end so nothing mutable escapes.
Immutability, and what a method actually returns
fun main() {
val name = "aurora"
val upper = name.uppercase()
println("name still: $name")
println("upper: $upper")
println("different object: ${name !== upper}")
val built = buildString {
append("BERTH")
append(' ')
append(4)
}
println("built: $built")
println("built length: ${built.length}")
val cargo = listOf("grain", "barley", "oats")
println("joined: ${cargo.joinToString(separator = ", ", prefix = "[", postfix = "]")}")
println("total chars in cargo: ${cargo.sumOf { it.length }}")
}
Output:
name still: aurora
upper: AURORA
different object: true
built: BERTH 4
built length: 7
joined: [grain, barley, oats]
total chars in cargo: 15
uppercase() did not touch name; it produced a second string and left the first exactly as it was, which is why the first line still reads in lower case. buildString took three appends of three different types -- a String, a Char and an Int -- and produced seven characters, because append is overloaded rather than generic and converts each argument as it goes. The last line is the check worth copying: five plus six plus four is fifteen, and sumOf on the lengths is how you verify that a join did not quietly drop an element.
Equality, and the one answer that depends on the platform
fun main() {
val a = "AURORA"
val b = "AUR" + "ORA"
val c = StringBuilder("AUR").append("ORA").toString()
println("a == b: ${a == b}")
println("a == c: ${a == c}")
println("a === c: ${a === c}")
println("case-insensitive: ${a.equals("aurora", ignoreCase = true)}")
println("apple before banana: ${"apple" < "banana"}")
println("blank then empty: ${" ".isBlank()} ${" ".isEmpty()}")
}
Output:
a == b: true
a == c: true
a === c: false
case-insensitive: true
apple before banana: true
blank then empty: true false
== on strings compares contents, so all three spellings of AURORA are equal, and === asks the different question of whether two references point at one object -- which the StringBuilder route guarantees they do not. Note what is deliberately not printed here: a === c is a guaranteed false, but a === b would print true on the JVM because the compiler folds two adjacent constants into one and the class file's constant pool hands out a single shared instance for it. That is a JVM implementation fact, not a Kotlin guarantee, and no program should be written to depend on it. The last line is the distinction that catches people out: two spaces are blank but not empty, and only isBlank treats whitespace as nothing.
Real World Example: The Quay Noticeboard, Set in Fixed-Width Columns
A departures board is a string problem with a hard constraint: every row has to occupy the same columns, because the board is read down a column rather than across a line. The source data is a block of raw text, the layout is four fixed widths, and the only interesting decision is which side of each field the padding goes on. Numbers pad on the left so their digits line up; names pad on the right so their first letters do.
const val SAILINGS = """
AURORA;LEEDS;0630;14
BELLONA;HULL;0745;9
CORVUS;YORK;1015;22
"""
const val W_VESSEL = 10
const val W_PORT = 8
const val W_DEP = 6
const val W_CREW = 4
fun row(vessel: String, port: String, dep: String, crew: String): String =
vessel.padEnd(W_VESSEL) + port.padEnd(W_PORT) + dep.padEnd(W_DEP) + crew.padStart(W_CREW)
fun main() {
val sailings = SAILINGS.trimIndent().lines().filter { it.isNotBlank() }
val header = row("VESSEL", "PORT", "DEP", "CREW")
val rule = "-".repeat(header.length)
println(header)
println(rule)
var crewTotal = 0
for (line in sailings) {
val parts = line.split(";")
crewTotal += parts[3].toInt()
println(row(parts[0], parts[1], parts[2], parts[3]))
}
println(rule)
println(row("ROWS", sailings.size.toString(), "CREW", crewTotal.toString()))
println("width: ${header.length} crew column starts at ${header.length - W_CREW}")
}
Output:
VESSEL PORT DEP CREW
----------------------------
AURORA LEEDS 0630 14
BELLONA HULL 0745 9
CORVUS YORK 1015 22
----------------------------
ROWS 3 CREW 45
width: 28 crew column starts at 24
The raw string did three jobs at once. It let the sailings be typed in the source with real line breaks and no escapes, it let them be indented under the declaration for legibility, and trimIndent() then removed exactly the indentation they shared along with the blank first and last lines that the triple quotes create. What comes back is three lines with no leading spaces, which is why split(";") finds the vessel name in field zero rather than a name with four spaces glued to the front. The filter on blank lines is defensive rather than necessary here, and it is worth keeping for the day somebody adds a trailing blank line to the block.
The widths are the whole layout, and pulling them out as constants is what makes the header, the rule and the totals row agree. row is called four different ways -- for the header, for each sailing, and for the totals -- so there is one definition of where a column starts and no chance of the header drifting away from the data underneath it. The rule is "-".repeat(header.length) rather than a hard-coded run of dashes for the same reason: change W_PORT to nine and every line in the output moves together.
The padding direction carries the meaning. padEnd on the three text fields puts the spaces after the value, so the letters begin at a fixed column and the eye can run down the list of vessels. padStart on the crew count puts the spaces before it, so the units digit of 9 sits under the units digit of 14 and of 22, which is what makes a column of numbers addable by eye. The final line reports both the total width and the column at which the crew field begins, which is the sort of thing worth printing once during development and asserting in a test afterwards: twenty-eight minus four is twenty-four, and every crew figure occupies characters twenty-five to twenty-eight of its line.
The limits start with a defect, not a rough edge. The design flaw is that padEnd widens but never truncates: a vessel called AURORA BOREALIS is eleven characters wide, so its row would be twenty-nine characters long and every field after it would shift one place right, silently, with no error and no warning anywhere in the output. A board that can misalign without complaining is worse than one that refuses the row, and the fix is either take(W_VESSEL) with a visible ellipsis or a validation pass that measures the widest value before printing anything. Beyond that: parts[3].toInt() throws NumberFormatException on any malformed line and parts[3] itself throws IndexOutOfBoundsException on a line with a missing field, so one bad character takes down the whole board; dep is carried as text and never validated, so 9999 would print happily as a departure time; the totals row reuses the vessel column for the word ROWS, so a vessel genuinely named ROWS would be indistinguishable from the summary line; and the whole thing assumes one character occupies one column, which stops being true the moment a name arrives containing a character outside the Basic Multilingual Plane.
Common Mistakes
- Building text with
+=inside a loop. Every iteration allocates a fresh string containing everything accumulated so far, so the work is quadratic in the output size and the garbage collector does all of it twice. A thousand ten-character appends copy roughly five million characters instead of ten thousand.buildString { }is the same code with one word changed and one buffer instead of a thousand.
- Discarding the result of a string method.
name.trim()does not trimname; it returns a trimmed copy and throws it away if you do not assign it. EveryStringmethod is like this, without exception, because the receiver is immutable. The compiler will not warn you, because ignoring a return value is legal.
- Writing a Windows path or a regex in an ordinary literal.
"C:\temp"contains a tab,"\d+"is a compile error, and neither problem is visible when you skim the line. Raw strings exist for exactly this:"""C:\temp"""and"""\d+"""mean what they say.
- Forgetting
trimIndent()on a raw string. The indentation you added so the literal would sit neatly under its declaration is part of the value, so the JSON you send has eight spaces before every line and the SQL you log is unreadable. CalltrimIndent()unless the leading whitespace is genuinely wanted, and remember it also drops a blank first and last line.
- Confusing
trimIndent()withtrimMargin(). The first works out the common indent for itself; the second looks for an explicit marker, a vertical bar by default, and cuts everything to the left of it. Mixing them up produces text that is either still indented or missing its first character on every line, and the two are not interchangeable becausetrimIndenthas no way to preserve deliberate indentation.
- Assuming
lengthcounts characters as a reader would. It counts UTF-16 code units, so a character outside the Basic Multilingual Plane counts as two and a combining accent counts separately from the letter it sits on. Column alignment, truncation and "maximum 100 characters" validation all get this wrong; usecodePointCountwhen the distinction matters, and never assume one unit is one column.
- Relying on
===or on interning. Two strings with the same contents may or may not be the same object depending on constant folding, the class file's constant pool and whetherintern()was ever called.==is the correct comparison for text and compiles to anequalscall that begins with a reference check anyway, so the identity test buys nothing but a bug.
- Using the default locale for case conversion. In a Turkish locale the upper case of a dotless i is not the letter you expect, which is how identifier comparison breaks in production for users in one country only. Kotlin's
uppercase()andlowercase()are locale-independent by design; if you need a locale, pass it explicitly and know why.
- Putting logic inside
${}. A template that reads"total: ${items.filter { it.active }.sumOf { it.price } / count}"is a calculation hidden in a message, unreadable in a diff and untestable on its own. Compute into a named local first. The template is for placing values, not for producing them.
Best Practices
- Use
buildString { }whenever the text is assembled in more than one step, andjoinToString()whenever it comes from a collection. Between them they cover almost every case where somebody would otherwise reach for a loop and a running string.
- Reach for a raw string plus
trimIndent()for anything multi-line: SQL, JSON, help text, expected values in tests. It keeps the literal legible in the source and keeps the source's indentation out of the value.
- Keep string templates to a single value or a single property access. Anything longer belongs in a local with a name that says what it is, which also gives you somewhere to put a breakpoint.
- Escape a literal dollar sign as backslash-dollar in ordinary literals, and remember that raw strings cannot escape it at all -- there, a literal dollar has to be interpolated as a one-character string.
- Pull fixed-width layouts into named constants and build every row, including the header and any totals, through one function. Then a width change is one edit and the columns cannot drift apart.
- Prefer
isNotEmpty(),isBlank()andisNullOrBlank()over hand-rolled comparisons against an empty literal. They say which of the three conditions you mean, and the nullable variants remove a null check as well.
- Make whitespace visible when you are debugging text. Replacing tabs and newlines with markers before printing, or printing the length alongside the value, turns a class of invisible bugs into a class of obvious ones.
- Treat locale and encoding as decisions rather than defaults. Pass an explicit
Localeto anything that formats for a human, use the locale-independent case functions for anything a machine compares, and specify the charset when text crosses into bytes.
Practice Exercises
- Rewrite the noticeboard so the whole board is assembled in one
buildString { }and printed with a singleprintln. Append a newline after each row explicitly. Then print the total length of the assembled board and check it against your own arithmetic: seven lines of twenty-eight characters plus one newline each.
- Write
fun visible(text: String): Stringthat returns the text with every tab replaced by[TAB], every newline by[NL]and every carriage return by[CR]. Call it on a three-line raw string and on the same text written as an ordinary literal with escapes, print both results and the length of each, and confirm the two are identical.
- Fix the alignment flaw. Before printing anything, work out the widest vessel name in the data and use that width -- or truncate names longer than the fixed width and mark the truncation with a full stop. Add a sailing for a vessel whose name is eleven characters long, print the board, and verify every line is still the same length.
- Declare
val rocket = "\uD83D\uDE80"and print only itslength, itscodePointCount(0, rocket.length)and the number ofCharvalues you get fromrocket.toCharArray().size. Do not print the string itself. Explain in a comment why the first and third numbers agree with each other and disagree with the second.