Pocket Studio Academy
HomePart 11.3

Strings, templates and escaping

Free lesson9 min read·4 questions

Almost everything a user reads is a String you built. Learn to slot values into text with templates, to get quote marks and new lines inside a quoted string, and to stop guessing about backslashes.

Look at your phone

Open any app and count the things on screen that are text. A greeting with your name in it. A score. A price. A date. A button label. An error message.

Nearly all of them were built — assembled out of a fixed part the programmer wrote and a changing part the app worked out a moment ago. "Hello, " never changes. "Ada" does.

The is the that holds text, and this lesson is about building good ones without tying yourself in knots.

Think of it like this

Think of a school letter home.

The office has one printed letter with gaps in it:

Dear ________, your child ________ was absent on ________.

One letter, three gaps. The office fills the gaps in differently for every family, and prints five hundred copies. Nobody rewrites the sentence each time.

That printed letter is a string template. The fixed words are typed once; the gaps get filled from whatever you have to hand. Kotlin marks a gap with a dollar sign.

Making text

Text goes between double quotes. Always double, never single — single quotes mean , exactly one character.

kotlin
1val greeting = "Hello"
2val empty = ""
3val spaced = "  Ada  "

Two strings can be glued together with +. This is called :

kotlin
1val first = "Ada"
2val last = "Lovelace"
3println(first + " " + last)   // Ada Lovelace

That works, and for two pieces it is fine. For four pieces it turns into a hunt for missing spaces, which is why Kotlin gives you something better.

Templates: the dollar sign

Put a $ in front of a name inside a string and Kotlin drops that value straight in:

kotlin
1val name = "Ada"
2val age = 36
3println("Hello, $name!")
4println("You are $age.")

This is a . It prints Hello, Ada! and You are 36.

For anything more than a plain name — a sum, a function call, a lookup — wrap it in curly brackets:

kotlin
1val age = 36
2println("Next year: ${age + 1}")
3println("Letters: ${name.length}")

The rule is short: $name for a bare name, ${anything} for everything else. When in doubt use the brackets; they are never wrong.

Tip

length is a of every String — how many characters it holds. Spaces count. "Ada".length is 3, and " Ada ".length is 5.

Escaping: getting awkward characters in

Here is a problem. A string is ended by a double quote. So how do you put a double quote inside one?

kotlin
println("She said "hello" quietly.")

Kotlin reads that as the string "She said ", then some rubbish. The fix is a backslash, which means "do not treat the next character normally":

kotlin
println("She said \"hello\" quietly.")

A backslash plus a character is an . There are five worth memorising:

You writeYou get
\"A double quote mark
\\One backslash
\nA new line
\tA tab
\$A dollar sign, not a template gap

\n is the useful one. A single println can produce several lines:

kotlin
println("Line one\nLine two")

And \$ matters the moment you print a price:

kotlin
1val cost = 5
2println("Cost: \$cost")   // Cost: $5

The first \$ is a real dollar sign. The second $ opens the template gap for cost. Read it slowly once and it stops looking like a cat walked over the keyboard.

When there is a lot of text

For several lines of fixed text, three quote marks in a row let you press Enter instead of writing \n everywhere. Nothing is escaped inside — quote marks are just quote marks:

kotlin
1val rules = """
2  Roll the dice.
3  Highest score wins.
4  Say "well played" afterwards.
5""".trimIndent()
6println(rules)

trimIndent() removes the leading spaces you added to keep the code tidy, so the output lines up on the left.

Comparing text

Use == to ask whether two strings hold the same characters:

kotlin
1val a = "ada"
2println(a == "ada")    // true
3println(a == "Ada")    // false

Capitals count. If you want to ignore them, compare in one case:

kotlin
println(a.uppercase() == "ADA")   // true

Putting it together

Try it in Pocket Studio
  1. Open Pocket Studio, tap Projects, and open KotlinLab.
  2. Open Lab.kt and clear out the inside of main.
  3. Type in the nine-line program from the walkthrough above.
  4. Tap Run. The Output panel should show seven lines: Hello, Ada!, Next year: 37, Letters: 3, She said "hi" quietly., Line one, Line two, Cost: $5.
  5. Count them. Six println calls made seven lines — the \n on line 8 is why. That is worth pausing on.
  6. Now change line 4 to use the older style: println("Hello, " + name + "!"). Run again. Identical output, more punctuation to get wrong. This is why templates exist.
  7. Break it once: delete one backslash from line 7 and run. Read the error, then put it back.
Error Doctor5 common errors
e: Expecting '"'
MeansA string was opened but never closed. Usually a missing quote at the end of the line, or an unescaped " in the middle that ended it early.
FixLook along the line for quote marks in pairs. Any quote that is meant to be printed needs a backslash in front of it: \".
e: Illegal escape: \d
MeansA backslash was followed by a character that means nothing to Kotlin. Only a handful of escapes exist.
FixIf you wanted a real backslash in the text, double it: \\. The legal escapes are \", \', \\, \n, \t, \r, \$ and \u.
e: Unresolved reference: nam
MeansA name inside a template does not exist — Kotlin looks names up inside strings exactly as it does outside them.
FixCheck the spelling in the $ gap. Also check the declaration is above the line using it.
e: Expecting an expression
MeansYou wrote ${} with nothing in the brackets, or the code inside them is incomplete.
FixPut something that produces a value inside the brackets, or delete the empty gap. If you wanted a literal dollar sign, write \$.
e: Unresolved reference: legth
MeansKotlin cannot find a property by that name on a String.
FixIt is length — l, e, n, g, t, h. Note that on a List the same idea is called size instead, which trips up nearly everybody once.
Recap
  • A is text in double quotes. Single quotes mean one .
  • with + works, but a reads better: $name for a plain name, ${...} for anything else.
  • A backslash starts an . The five to know are \", \\, \n, \t and \$.
  • Triple quotes hold several lines of text without escaping; finish with .trimIndent().
  • == compares the actual characters, and capitals count.
  • Next: numbers get their turn — the operators, the order they run in, and the single most surprising rule in Kotlin arithmetic.