1. Introduction
If you are just starting to program, strings seem as innocent as it gets: just text. But the compiler has a different opinion. For it, a string is a piece of source code that must be parsed according to rules. And some characters inside a string literal have a special meaning: they either terminate the string or switch on a “special mode”. Escaping is a way to tell the compiler: “Yes, I know this is a special character, but right now it should become ordinary text.”
Imagine you are writing a letter, but every word STOP suddenly means “finish the letter and send it”. At some point you will want to write the word STOP as a word, not as a command. Escaping is your “quote mode”: it turns the “command” back into “letters on paper”.
Regular string "..." and special characters
In Kotlin, a regular string is written in double quotes:
val s = "Hello!"
From this point on, the compiler carefully watches two things.
First, a double quote " inside a string terminates the string. That is, if you just write:
val s = "He said: "Hello""
the compiler will honestly try to understand why the string suddenly ended after He said: , and why some kind of chaos follows.
Second, a backslash \ inside a string is not “just a slash”, but a signal: “An escape sequence is coming.” That is, \n is not two characters \ and n, but one special “newline” character.
These two rules (quote terminates the string; backslash starts an escape) are the main sources of “why doesn’t this compile?” in strings. And these are exactly what we will tame today.
2. Escape sequences: \n and \t
When you write \n inside a regular string, Kotlin creates one character that means a line break (Enter). In other words, output will continue on a new line.
When you write \t, that is a tab character — a “tab” that usually looks like several spaces, but in reality is a separate control character. It is useful when you want to quickly align text columns without complex formatting.
Let’s look at this with a mini example. We will continue developing one more educational console app: NoteKeeper — a small note notebook. It is not “smart” yet, but it is honest.
fun main() {
println("NoteKeeper\n1) Add a note\n2) Show all\n0) Exit")
}
Here \n makes the text multi-line. The output will look roughly like this:
NoteKeeper
1) Add a note
2) Show all
0) Exit
Now an example with tabs:
fun main() {
println("Command\tDescription")
println("add\tAdd a note")
println("list\tShow all")
}
I wrote the output of this program next to it in comments:
fun main() {
println("Command\tDescription") // Command Description
println("add\tAdd a note") // add Add a note
println("list\tShow all") // list Show all
}
For now, do not try to turn \t into an “Excel-level perfect table”. It is a simple tool. If strings have different lengths, tabs will not always produce perfectly even columns — but for learning menus and hints, it is totally fine.
3. Escaping quotes and backslash
Now let’s take two of the most popular “string breakers”.
How to print a double quote " inside a string
To prevent a quote from terminating the string, you need to escape it: \".
fun main() {
val quote = "He said: \"Hello\""
println(quote) // He said: "Hello"
}
That is, \" inside a string means “insert a regular quote character into the text”.
This is especially useful when you want to nicely show user input or data in a report. For example: Note "Buy milk" added.
How to print a backslash \ inside a string
To get one \ character inside a regular string, you need to write two: \\.
fun main() {
val path = "C:\\Users\\alex\\notes.txt"
println(path) // C:\Users\alex\notes.txt
}
Why is that? Because the first \ says “I’m starting an escape sequence”, and the second clarifies “specifically, I need a backslash character”.
And this is where the classic trap lives:
fun main() {
val bad = "C:\new\test"
println(bad)
}
It looks like a “path”. But in reality Kotlin will see \n (newline) and \t (tab). So the string turns into an unexpected mess, and you will stare at the output for a long time thinking “I just wanted to save a file”. Kotlin is not to blame — the backslash is, because it is a special character.
4. String templates and the $ character
String templates in Kotlin are a way to insert values directly into a string without + concatenation: $a for a name and ${...} for an expression.
Substituting variables and expressions
The simplest option is to substitute a variable:
fun main() {
val title = "Plans for the day"
println("Note: $title") // Note: Plans for the day
}
If you need to insert an expression rather than just a name, curly braces are used:
fun main() {
val a = 7
val b = 5
println("$a + $b = ${a + b}") // 7 + 5 = 12
}
Read it like this: “insert a, insert b, then compute a + b and insert the result”. The practical rule is simple: a name goes without braces; an expression goes inside ${...}.
Trap: why $a + b is not the same as ${a + b}
A very typical beginner mistake: you want to print the sum, you write it “like a human”, and you get the wrong result.
fun main() {
val a = 2
val b = 3
println("$a + $b = $a + $b") // 2 + 3 = 2 + 3
}
From Kotlin’s point of view, this is perfectly logical: $a is variable substitution for a, then text + , then substitution $b, then text = , then again $a, then text + , then $b. There was no sum here.
And now the correct version:
fun main() {
val a = 2
val b = 3
println("$a + $b = ${a + b}") // 2 + 3 = 5
}
Curly braces enable “expression mode”. And this rule is worth remembering as a reflex: as soon as there is at least one operator (+, -, *, /), a function call, or a property access inside the substitution — you always need ${...}.
How to print $ as plain text
$ in Kotlin marks the start of a string template. Therefore, an attempt to write:
val s = "Price: $"
will end with a compilation error: Kotlin expects a name after $ ($price) or { (${price}), but you just ended the string.
The correct way to print the $ sign as text is to escape it: "\$".
fun main() {
val price = 19
println("Price: \$${price}") // Price: $19
}
Let’s break it down by characters once so it is clear.
At the beginning \$ prints a literal dollar sign. Then ${...} substitutes the number. The result is $19.
In NoteKeeper this will be useful, for example, if we decide to store expense notes (for now just as text). Suppose a note is: Coffee $4. Then the output might look like this:
fun main() {
val item = "Coffee"
val cost = 4
println("Purchase: $item, price: \$${cost}") // Purchase: Coffee, price: $4
}
Sometimes a “super-smart string” is worse than two val variables
At this point a temptation often appears: “Oh, templates can do expressions! Let’s cram everything in there!” And you end up with a string that looks like a spell in an ancient language.
Technically, Kotlin allows fairly complex expressions inside ${...}. But good style is: calculate first, then insert. This makes the code more readable, and it is easier for you (and your future colleagues, and your future “me one week later”) to debug.
Compare two variants. The too-smart version:
fun main() {
val a = 10
val b = 3
println("Result: ${a / b}, remainder: ${a % b}") // Result: 3, remainder: 1
}
This is still tolerable, but already on the edge. The second version is much better:
fun main() {
val a = 10
val b = 3
val div = a / b
val rem = a % b
println("Result: $div, remainder: $rem") // Result: 3, remainder: 1
}
Here your names gain meaning: div and rem. And it is much easier to read.
Kotlin encourages string templates instead of concatenation. But “use templates” does not mean “hide all logic inside templates”. Templates are about output; computations are better done separately.
6. NoteKeeper: messages and menu
Now we will do a small (but very realistic) upgrade of our console NoteKeeper: we will learn to print clear messages that contain quotes, line breaks, and templates.
Let’s imagine we already have a fixed-size array of notes, we add one note, and then print a confirmation.
fun main() {
val notes = Array(5) { "" }
var count = 0
val newNote = "Buy milk"
notes[count] = newNote
count++
println("Added: \"$newNote\" (total notes: $count)")
// Added: "Buy milk" (total notes: 1)
}
Here we showed the note in quotes via \" so the user can see the text boundaries. We used $newNote and $count so we would not have to glue strings with +. And we got a readable string where it is easy to see what exactly is being printed.
Now let’s make a simple menu as a single string with \n, so we can print it with one command:
fun main() {
val menu =
"NoteKeeper\n" +
"1) Add a note\n" +
"2) Show all\n" +
"0) Exit"
println(menu)
}
Yes, there is + here. For now, we are using it deliberately: multi-line raw strings """...""" will be in the next lecture, and there you will see a much nicer approach. For now, your goal is to understand what \n is and why it works.
7. Typical mistakes with escaping and string templates
Mistake No. 1: forgetting that \ in a regular string is a special character.
Most often this shows up with Windows paths. The string "C:\new\test" unexpectedly turns into “C:”, then a line break because of \n, then a tab because of \t, and then some other weird characters. If you need a literal backslash, write \\.
Mistake No. 2: trying to insert an expression without ${...}.
"$a + $b = $a + $b" looks plausible, but it is just text. To compute the sum, you need the expression template: "${a + b}". This rule follows from the string templates model in Kotlin: a name is $a, an expression is ${...}.
Mistake No. 3: trying to print $ as a regular character and getting a compilation error.
The string "Price: $" does not “print a dollar sign” — it fails, because $ starts a template. To print a dollar sign, use "\$", and if you need a number next to it, combine \$ and ${price} as in "\$${price}".
Mistake No. 4: overloading one string with computations and then being unable to debug it.
When there is too much ${...} inside "...", especially with operators and complex expressions, the string turns into a puzzle. It is much calmer to compute values in separate val variables first and then print them with simple $name.
Mistake No. 5: confusing the effect of println and \n.
println() already adds a newline at the end. If you write println("Hello\n"), you will get an extra blank line (or an extra line break) where you did not expect it. This is not tragic, but in menus and reports it quickly leads to “why did everything shift?”.
GO TO FULL VERSION