Part 02 / Topic 3 of 8
String templates
A string template inserts a value straight into a string literal with $, instead of
stitching pieces together with +.
fun main() {
val diner = "Priya"
val city = "Bengaluru"
val dosaPrice = 180
val coffeePrice = 60
// Simple form: $name, for a single variable
println("Diner: $diner, City: $city")
// Expression form: ${...}, for anything more than a bare name
println("Total for one dosa and one coffee: ${dosaPrice + coffeePrice}")
val cart = listOf("Masala Dosa", "Filter Coffee", "Rava Idli")
println("Items ordered: ${cart.size} (${cart})")
// Concatenation with + still works, but a template reads better once more than one value is mixed in
val oldStyle = "Diner: " + diner + ", City: " + city
println(oldStyle)
// $ is special inside a string literal, escape it with \$ to print a literal dollar sign
println("Price tag written the US way: \$${dosaPrice}")
// ₹ is a plain character, not a template marker, so it needs no escaping
println("Price tag written the Indian way: ₹$dosaPrice")
}
$ kotlinc 03_string_templates.kt -include-runtime -d 03.jar
$ java -jar 03.jar
Diner: Priya, City: Bengaluru
Total for one dosa and one coffee: 240
Items ordered: 3 ([Masala Dosa, Filter Coffee, Rava Idli])
Diner: Priya, City: Bengaluru
Price tag written the US way: $180
Price tag written the Indian way: ₹180
$diner works because it's a bare name; dosaPrice + coffeePrice needs the ${...} form because
it's an expression, not just a name. println("Items ordered: ${cart.size} (${cart})") also shows
that a template calls toString() on whatever you put inside it — cart prints as
[Masala Dosa, Filter Coffee, Rava Idli], the same square-bracket form println(cart) alone
would produce. The two \$/₹ lines are a reminder that $ is Kotlin syntax inside a string
literal, so writing a literal US-style price needs \$; ₹ carries no such meaning to Kotlin, so
it needs nothing special.
Full program: examples/03_string_templates.kt.
Done here? The practice set for Part 2 — including the solutions — is on the part page.