1. Introduction
If you’re just starting to program, strings seem as innocent as it gets: it’s just text. But the compiler has a different opinion. For it, a string is a piece of source code that must be parsed by rules. And some characters inside a string literal have 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 must be treated as plain text.”
Imagine you’re writing a letter, but every time the word STOP appears it suddenly means “finish the letter and send it”. At some point you’ll want to write the word STOP as a word, not as a command. Escaping is your “quote mode”: it turns a “command” back into “letters on paper”.
Regular string "..." and special characters
In Kotlin, a regular string is written in double quotes:
val s = "안녕하세요!"
From this moment on, the compiler starts carefully watching two things.
First, the double quote " inside a string closes the string. That is, if you just write:
val s = "그가 말했다: "안녕""
the compiler will honestly try to figure out why the string suddenly ended after 그가 말했다: , and then some kind of chaos follows.
Second, the backslash \ inside a string is not “just a slash”, but a signal: “An escape sequence is coming now.” That is, \n is not two characters \ and n, but one special “newline” character.
These two rules (a quote closes the string, a slash starts an escape) are the main sources of “why doesn’t it compile” with strings. And these are exactly what we’ll tame today.
2. Escape sequences: \n and \t
When you write \n inside a regular string, Kotlin creates a single character that means a line break (Enter). So output continues on a new line.
When you write \t, that’s a tab character—“tab”, which usually looks like several spaces visually, but is actually a separate control character. It’s useful when you want to quickly align text columns without complex formatting.
Let’s look at this with a mini example. We’ll continue developing another educational console app: NoteKeeper—a small note pad. It’s not “smart” yet, but it’s honest.
fun main() {
println("NoteKeeper\n1) 노트 추가\n2) 전체 보기\n0) 종료")
}
Here \n makes the text multi-line. The output will be approximately like this:
NoteKeeper
1) 노트 추가
2) 전체 보기
0) 종료
Now an example with tabs:
fun main() {
println("명령\t설명")
println("add\t노트 추가")
println("list\t전체 보기")
}
I wrote this program’s output next to it in comments:
fun main() {
println("명령\t설명") // 명령 설명
println("add\t노트 추가") // add 노트 추가
println("list\t전체 보기") // list 전체 보기
}
For now, don’t try to turn \t into an “Excel-level perfect table”. It’s a simple tool. If strings have different lengths, tabs won’t always produce perfectly aligned columns—but for learning menus and hints, it works just fine.
3. Escaping quotes and backslash
Now let’s take the two most popular “string breakers”.
How to print a double quote " inside a string
So the quote doesn’t close the string, you must escape it: \".
fun main() {
val quote = "그가 말했다: \"안녕\""
println(quote) // 그가 말했다: "안녕"
}
That is, \" inside a string means “insert a normal quote character into the text”.
This is especially useful when you want to nicely show the user input or data in a report. For example: 노트 "우유 사기"가 추가됨.
How to print a backslash \ inside a string
To get a single \ 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? Because the first \ says “I am starting an escape sequence”, and the second clarifies “specifically—I need a backslash character”.
And here’s 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). The string turns into unexpected mush, and you’ll stare at the output for a long time thinking “I just wanted to save a file”. Kotlin isn’t to blame—the backslash is special inside strings.
4. String templates and the $ symbol
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 substituting a variable:
fun main() {
val title = "오늘의 계획"
println("노트: $title") // 노트: 오늘의 계획
}
If you need to insert an expression rather than just a name, use curly braces:
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—without braces; an expression—in ${...}.
Trap: why $a + b is not the same as ${a + b}
A very typical beginner mistake: you want to print a sum, you write it “like a human”, and you get something else.
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 substitution of variable a, then comes text + , then substitution $b, then text = , then again $a, then text + , then $b. There was no sum here.
And now the correct variant:
fun main() {
val a = 2
val b = 3
println("$a + $b = ${a + b}") // 2 + 3 = 5
}
Curly braces enable “expression mode”. This rule is worth memorizing as a reflex: as soon as there is at least one operator (+, -, *, /), a function call, or a property access inside the substitution—always use ${...}.
How to print $ as plain text
In Kotlin, $ starts a string template. So trying to write:
val s = "가격: $"
will end with a compilation error: Kotlin expects after $ either a name ($price) or a { (${price}), but you just ended the string.
The correct way to print a $ sign as text is to escape it: "\$".
fun main() {
val price = 19
println("가격: \$${price}") // 가격: $19
}
Let’s break it down by characters once so it’s clear.
At the start \$ prints a literal dollar. Then ${...} substitutes the number. The result is $19.
In NoteKeeper this can be useful, for example, if we want to store expense-notes (for now just as text). Suppose a note is: Coffee $4. Then the output can look like:
fun main() {
val item = "커피"
val cost = 4
println("구매: $item, 가격: \$${cost}") // 구매: 커피, 가격: $4
}
Sometimes a “super-smart string” is worse than two val
At this point there’s often a temptation: “Oh, templates can do expressions! Let’s shove 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: compute first, then insert. It makes code more readable, and it’s easier for you (and your future colleagues, and your future “me one week later”) to debug.
Compare two variants. The too-smart variant:
fun main() {
val a = 10
val b = 3
println("결과: ${a / b}, 나머지: ${a % b}") // 결과: 3, 나머지: 1
}
This is still tolerable, but already borderline. The second variant is much better:
fun main() {
val a = 10
val b = 3
val div = a / b
val rem = a % b
println("결과: $div, 나머지: $rem") // 결과: 3, 나머지: 1
}
Here the names gain meaning: div and rem. And it’s much easier to read.
Kotlin encourages string templates instead of concatenation. But “use templates” is not the same as “hide all logic inside templates”. Templates are for output; calculations are better done separately.
6. NoteKeeper: messages and menu
Now we’ll do a small (but very real-life) upgrade of our console NoteKeeper: we’ll learn to print clear messages that contain quotes, line breaks, and templates.
Let’s imagine we already have an array of notes with a fixed size, we add one note, and then print a confirmation.
fun main() {
val notes = Array(5) { "" }
var count = 0
val newNote = "우유 사기"
notes[count] = newNote
count++
println("추가됨: \"$newNote\" (총 노트 수: $count)")
// 추가됨: "우유 사기" (총 노트 수: 1)
}
Here we showed the note in quotes using \" so the user can see the text boundaries. We used $newNote and $count to avoid stitching strings with +. And we got a readable string where it’s easy to see what exactly gets 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) 노트 추가\n" +
"2) 전체 보기\n" +
"0) 종료"
println(menu)
}
Yes, there is + here. We use it deliberately for now: multi-line raw strings """...""" will be in the next lecture, and there you’ll see a much nicer way. For now, your goal is to understand what \n is and why it works.
7. Common mistakes with escaping and string templates
Mistake 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 newline due to \n, then a tab due to \t, and then some other strange characters. If you need a literal backslash, write \\.
Mistake 2: trying to insert an expression without ${...}.
"$a + $b = $a + $b" looks plausible, but it’s just text. To compute the sum you need an expression template: "${a + b}". This rule follows from the string templates model in Kotlin itself: a name is $a, an expression is ${...}.
Mistake 3: trying to print $ as a normal character and getting a compilation error.
The string "가격: $" does not “print a dollar”, it breaks because $ starts a template. To print a dollar sign, use "\$", and if you need a number next to it—combine \$ and ${price} like in "\$${price}".
Mistake 4: overloading one string with calculations and then being unable to debug it.
When there are too many ${...} inside "...", especially with operators and complex expressions, the string turns into a riddle. It’s much calmer to compute values into separate val first, and then print them with simple $name.
Mistake 5: mixing up the effect of println and \n.
println() already adds a newline at the end. If you write println("안녕\n"), you’ll get an extra empty line (or an extra line break) where you didn’t expect it. It’s not a tragedy, but in menus and reports it quickly leads to “why did everything shift”.
GO TO FULL VERSION