String Templates
In this page:
Simple Variable Templates
Placing a dollar sign directly before a variable name inside a string, like $name, inserts that variable's current value into the string without needing concatenation.
Example: Simple Variable Templates
fun main() {
val name = "Kotlin"
val version = 2
println("Language: $name, Version: $version")
}
Login to try C/C++/Java/PHP code in the editor
Expression Templates with Curly Braces
For anything more than a plain variable name -- property access, function calls, or arithmetic -- wrap the expression in ${ } so Kotlin evaluates it and inserts the result.
Example: Expression Templates with Curly Braces
fun main() {
val a = 5
val b = 3
println("Sum: ${a + b}, Product: ${a * b}")
}
Login to try C/C++/Java/PHP code in the editor
Templates with Object Properties
String templates can reach into an object's properties directly inside ${ }, which is much cleaner than building the string with multiple concatenations.
Example: Templates with Object Properties
data class Point(val x: Int, val y: Int)
fun main() {
val p = Point(3, 4)
println("Point is at (${p.x}, ${p.y})")
}
Login to try C/C++/Java/PHP code in the editor
Escaping a Literal Dollar Sign
When a string needs an actual $ character rather than starting a template, escape it with a backslash as \$.
Example: Escaping a Literal Dollar Sign
fun main() {
val price = 20
println("Price: \$$price")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the curly braces around an expression more complex than a single variable, like
$user.nameinstead of${user.name}. - Trying to use string concatenation with
+everywhere out of habit instead of the more readable$variablesyntax. - Forgetting to escape a literal dollar sign with
\$when it should not start a template.
$variableNameinside a string inserts that variable's value directly.${expression}with curly braces is required for anything beyond a simple variable name, such as a property access or a calculation.- A literal dollar sign in a string must be escaped as
\$to avoid being treated as a template. - String templates work inside both single-line and triple-quoted strings.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: