Skip to the workspace
Pebellslearn by building
Comments and Printing Data  ›  Capstone Project

String Templates

String Templates 12 minA string template inserts a name with $name or an expression with ${expression}. Literal dollar signs require the appropriate escaping or template form.

kotlin / String Templates

Explore each scene at your own pace.

01 · The rule

The rule

String Templates

A string template inserts a name with $name or an expression with ${expression}. Literal dollar signs require the appropriate escaping or template form.

Build a message from values and expressions without losing their meaning.

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
  • $name inserts 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 an if.
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.)

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.