Strings, templates and escaping
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 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.
1val greeting = "Hello"
2val empty = ""
3val spaced = " Ada "Two strings can be glued together with +. This is called :
1val first = "Ada"
2val last = "Lovelace"
3println(first + " " + last) // Ada LovelaceThat 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:
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:
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.
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?
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":
println("She said \"hello\" quietly.")A backslash plus a character is an . There are five worth memorising:
| You write | You get |
|---|---|
\" | A double quote mark |
\\ | One backslash |
\n | A new line |
\t | A tab |
\$ | A dollar sign, not a template gap |
\n is the useful one. A single println can produce several lines:
println("Line one\nLine two")And \$ matters the moment you print a price:
1val cost = 5
2println("Cost: \$cost") // Cost: $5The 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:
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:
1val a = "ada"
2println(a == "ada") // true
3println(a == "Ada") // falseCapitals count. If you want to ignore them, compare in one case:
println(a.uppercase() == "ADA") // truePutting it together
- Open Pocket Studio, tap Projects, and open KotlinLab.
- Open
Lab.ktand clear out the inside ofmain. - Type in the nine-line program from the walkthrough above.
- 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. - Count them. Six
printlncalls made seven lines — the\non line 8 is why. That is worth pausing on. - 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. - Break it once: delete one backslash from line 7 and run. Read the error, then put it back.
" in the middle that ended it early.\".\\. The legal escapes are \", \', \\, \n, \t, \r, \$ and \u.$ gap. Also check the declaration is above the line using it.${} with nothing in the brackets, or the code inside them is incomplete.\$.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.- A is text in double quotes. Single quotes mean one .
- with
+works, but a reads better:$namefor a plain name,${...}for anything else. - A backslash starts an . The five to know are
\",\\,\n,\tand\$. - 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.