← Back to Kotlin Course | Chapter 2: Variables & Types | Lesson 4 of 7

String Templates

String templates let you drop a variable's value directly inside a piece of text just by putting a dollar sign in front of it.

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

markup
fun main() {
    val name = "Kotlin"
    val version = 2
    println("Language: $name, Version: $version")
}

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

markup
fun main() {
    val a = 5
    val b = 3
    println("Sum: ${a + b}, Product: ${a * b}")
}

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

markup
data class Point(val x: Int, val y: Int)

fun main() {
    val p = Point(3, 4)
    println("Point is at (${p.x}, ${p.y})")
}

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

markup
fun main() {
    val price = 20
    println("Price: \$$price")
}
Common Mistakes
  1. Forgetting the curly braces around an expression more complex than a single variable, like $user.name instead of ${user.name}.
  2. Trying to use string concatenation with + everywhere out of habit instead of the more readable $variable syntax.
  3. Forgetting to escape a literal dollar sign with \$ when it should not start a template.
Chapter Summary
  • $variableName inside 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.