Strings, Chars and Booleans
Each run in the logbook needs a line a person can read: "Asha ran 8.5 km". Building that line means mixing text with numbers, and deciding whether a run counts as long means working with true and false.
The rule
Double quotes for text, single for one character;
sputs values inside.
val name = "Asha" // String
val initial = 'A' // Char: exactly one character
val km = 8.5
val line = s"$name ran $km km" // "Asha ran 8.5 km"- A String is text in double quotes. Scala strings are Java strings, and they are immutable:
name.toUpperCasereturns a new string,"ASHA", and leavesnamealone. - A Char is one character in single quotes.
'A'and"A"are different types. - An interpolated string starts with
s. Inside it,$nameinserts a value and${…}inserts the result of any expression:s"${km * 1000} metres"gives"8500.0 metres". - The
finterpolator formats numbers as well:f"$km%.2f km"gives"8.50 km", with exactly two decimal places. - Triple quotes make a string that can run over several lines:
val notice = """Saturday long run
Meet at the boathouse, 7 am"""Handy string methods: name.length is 4, " Ben ".trim is "Ben", and clubName.contains("Run") is true. The + operator joins strings: "Asha" + " ran".
A Boolean is true or false, and comparisons produce one:
val longRun = km >= 10 // false
val finished = trueConditions in Scala must be real Booleans. if 1 then … or if name then … is a compile error; unlike Python or JavaScript, there are no "truthy" or "falsy" values.
The shortcut
Read the first character of a literal: " means String, ' means Char, s" means text with values spliced in, f" means text with formatted numbers. When output shows a literal $, look for a missing s.
Collect the values
nameis"Asha"andkmis8.5.
Drills
Answer fast — trust the rule.
What is the difference between 'A' and "A"?
val name = "Asha" then println("$name ran"). What is printed?
What does s"${8.5 * 2} km" produce?
With val km = 8.5, what is f"$km%.2f km"?
What happens with if 1 then "yes" else "no"?
Remember
- Double quotes make a String, single quotes a Char;
s"…"splices values andf"…"formats numbers. - Read the first character of a literal to know its kind; a stray
$in output means a missings. - Trap: expecting truthy values — conditions must be Booleans.
