String Templates
The café's end-of-day line should read "Pebble Café sold 42 cups for 147.0 today". Gluing that together with + is fiddly and easy to get wrong. Kotlin lets you write the sentence as it should look and drop the values straight into it.
The rule
$name for a name, ${…} for anything bigger.
val cafe = "Pebble Café"
val cups = 42
val price = 3.5
println("$cafe sold $cups cups for ${cups * price} today")
// Pebble Café sold 42 cups for 147.0 today$nameinserts the value of a variable. Kotlin reads letters, digits and underscores after the$as the name and stops at anything else.${expression}inserts the result of any expression: arithmetic, a property, a function call, even anif.
println("Name has ${cafe.length} characters") // 11
println("Status: ${if (cups > 40) "busy" else "quiet"}")Any value works, because templates call toString() just like println does. A list inside a template shows as [latte, chai].
Dollar signs. A $ followed by a letter always starts a template. For a literal dollar there, write \$: "\$cups" prints the text $cups. A $ before a digit or a space is already plain text, so "Cost: $5" is fine as it is. Raw strings (triple quotes) do not process backslash escapes, so there you write ${'$'}.
Formatting numbers. Templates print a Double with as many digits as it needs: 3.0 * 1.1 shows 3.3000000000000003. To fix the decimals, format first: "%.2f".format(total) gives "3.30". (The decimal separator follows the computer's locale settings.)
The shortcut
At every $, ask: "Does the thing I want end at the first dot, bracket or space?" If yes, $name is enough. If no, wrap it in braces.
The goal
Print "Pebble Café has 11 letters".
This dot trap is the most common template bug, and it compiles without complaint, so you only notice it in the output.
Drills
Answer fast — trust the rule.
With val cups = 3, what does "Sold $cups cups" produce?
With val name = "chai", what does "$name.length" produce?
Which template correctly inserts the total of cups * price?
With val price = 5 in scope, which normal string prints the literal text $price?
With val total = 7.5, what does "%.2f".format(total) give (in an English locale)?
Remember
$namefor a simple name,${ }for any expression.$name.lengthprints the name then the text ".length"; use braces.- Escape a literal dollar with
\$; format decimals with"%.2f".format(x).
