Kotlin String Templates
String templates let you embed variables and expressions directly inside a string. Instead of breaking a string apart and joining it with +, you write the variable name right inside the text using a $ sign.
Basic String Template
val name = "Sara"
println("Hello, $name!") // Hello, Sara!The $name part gets replaced by the actual value of name when the line runs.
Without vs With String Templates
Without templates (old way):
val city = "Paris"
val msg = "Welcome to " + city + "! Population: " + 2_000_000
─────────────────────────────────────────────────────────────
With string templates (Kotlin way):
val city = "Paris"
val msg = "Welcome to $city! Population: 2000000"
Much cleaner and easier to read.
Embedding Expressions with ${}
When you need to embed a calculation or a function call — not just a variable — use ${} with curly braces.
val price = 100
val tax = 18
println("Price: $price")
println("Tax: $tax")
println("Total: ${price + tax}") // Total: 118
println("Tax rate: ${tax.toDouble() / price * 100}%") // Tax rate: 18.0%Diagram: How Template Resolution Works
val username = "Leo"
val score = 850
val message = "Player $username scored ${score * 2} points!"
Step 1: Find $username → replace with "Leo"
Step 2: Find ${score * 2} → evaluate 850 * 2 = 1700, replace
Step 3: Result → "Player Leo scored 1700 points!"
Calling Functions Inside Templates
val word = "kotlin"
println("Original: $word")
println("Upper: ${word.uppercase()}")
println("Length: ${word.length}")
println("First char: ${word[0]}")Output:
Original: kotlin
Upper: KOTLIN
Length: 6
First char: kUsing $ in a String (Literal Dollar Sign)
To print an actual dollar sign character without triggering a template, use \$:
val amount = 250
println("You owe \$$amount") // You owe $250Templates in Multiline Strings
val firstName = "Anjali"
val lastName = "Sharma"
val age = 30
val profile = """
Name : $firstName $lastName
Age : $age
Born : ${2024 - age}
""".trimIndent()
println(profile)Output:
Name : Anjali Sharma
Age : 30
Born : 1994Practical Example: Invoice Generator
fun main() {
val customer = "Raj Electronics"
val item = "LED TV 55 inch"
val qty = 3
val unitPrice = 32000.0
val taxRate = 0.12
val subtotal = qty * unitPrice
val tax = subtotal * taxRate
val total = subtotal + tax
println("""
─────────────────────────────
INVOICE
Customer : $customer
Item : $item
Quantity : $qty
Unit Price: ₹$unitPrice
Subtotal : ₹$subtotal
Tax (12%): ₹$tax
Total : ₹$total
─────────────────────────────
""".trimIndent())
}Output:
─────────────────────────────
INVOICE
Customer : Raj Electronics
Item : LED TV 55 inch
Quantity : 3
Unit Price: ₹32000.0
Subtotal : ₹96000.0
Tax (12%): ₹11520.0
Total : ₹107520.0
─────────────────────────────String templates remove the need to concatenate strings manually. They make the code shorter and the output format obvious just from reading the string itself.
