String Templates
String templates let you embed variables and expressions inside string literals using $ or ${}. They are more readable than string concatenation and are widely used in Kotlin.
Syntax
// Embed a variable.
"Hello, $name"
// Embed an expression (curly braces required).
"Total: ${price * count}"
// Raw string (triple quotes).
"""
multi-line
string
"""
Syntax Overview
| Syntax | Description |
|---|---|
| $variableName | Embeds the value of a variable into the string. Curly braces are required if a letter, digit, or underscore immediately follows the variable name. |
| ${expression} | Evaluates any expression and embeds the result. Method calls and arithmetic expressions are supported. |
| """...""" | A raw string. It can contain newlines and backslashes without escaping. |
| trimIndent() | Removes the common leading indentation from a raw string. Lets you keep code indentation while keeping the string clean. |
| trimMargin() | Removes everything up to a specified character (default: |) at the start of each line. |
Sample Code
fun main() {
val name = "Taro"
val age = 25
// Embed a variable.
println("Hello, $name") // Prints "Hello, Taro".
// Embed an expression.
println("Next year you will be ${age + 1}.") // Prints "Next year you will be 26.".
// Method calls can also be embedded.
val items = listOf("apple", "orange", "grape")
println("There are ${items.size} items.") // Prints "There are 3 items.".
println("Uppercase: ${name.uppercase()}") // Prints "Uppercase: TARO".
// Raw string (newlines and tabs are included as-is).
val json = """
{
"name": "$name",
"age": $age
}
""".trimIndent()
println(json)
// Prints:
// {
// "name": "Taro",
// "age": 25
// }
// To output a literal $ sign, write ${'$'}.
val price = 500
println("Price: ${'$'}$price") // Prints "Price: $500".
// Example using trimMargin.
val text = """
|Line 1
|Line 2
|Line 3
""".trimMargin()
println(text)
// Prints "Line 1", "Line 2", and "Line 3" each on its own line.
}
Notes
String templates produce more readable code than concatenation like "Hello, " + name + "!". If a letter immediately follows a variable name (e.g., ${count}items), omitting the curly braces causes Kotlin to treat the suffix as part of the variable name. Always use ${} in such cases.
Raw strings are especially useful for content with many escape characters, such as regular expression patterns or JSON. See Basic Data Types for primitive types, and val / var for variable declarations.
If you find any errors or copyright issues, please contact us.