String Templates
Embedding variables and expressions directly inside strings instead of concatenating pieces by hand.
អាន 2 នាទី
Building text out of pieces is one of the most common things any program does, and Kotlin makes it noticeably less painful than manual concatenation with a feature called string templates.
The $variable syntax
Prefix a variable name with $ inside a string, and Kotlin substitutes its value:
val name = "Alice"
val age = 30
println("Hello, $name! You are $age years old.")
// Hello, Alice! You are 30 years old.Compare that to the equivalent with concatenation:
println("Hello, " + name + "! You are " + age + " years old.")The template version reads closer to the sentence you're actually building, and it avoids the easy mistake of forgetting a space or a + somewhere in a long chain.
Embedding expressions with ${ }
For anything beyond a plain variable name — a property access, a function call, or a calculation — wrap the expression in ${ }:
val items = listOf("apple", "banana", "cherry")
println("You have ${items.size} items.")
println("Total price: $${items.size * 2}")
println("First item, uppercase: ${items[0].uppercase()}")Without the braces, $items.size would only substitute items and then print the literal text .size afterward — the braces tell Kotlin where the expression starts and ends.
Multi-line strings
Triple-quoted strings span multiple lines and don't require escaping most special characters, which makes them convenient for things like SQL snippets, JSON samples, or formatted output:
val query = """
SELECT id, name
FROM users
WHERE age > $age
""".trimIndent()
println(query).trimIndent() strips the common leading whitespace from every line, so the string isn't polluted with the indentation of the surrounding Kotlin code.
Escaping a literal dollar sign
If you need an actual $ character rather than a template, escape it:
val price = 4.99
println("Price: \$${price}") // Price: $4.99Why this matters beyond convenience
String templates aren't just shorter — they reduce a real class of bug. Every extra + in a concatenation chain is a place to drop a space, mismatch a type, or lose track of parentheses in a calculation. Because the expression inside ${ } is regular Kotlin code, checked by the same compiler as everything else, a typo like ${items.szie} is caught immediately rather than surfacing as a wrong string at runtime.
Now that you can build readable text out of values, the next lesson covers a feature templates rely on constantly: how Kotlin represents the absence of a value, and how it forces you to handle that possibility safely.