0
0
KotlinConceptBeginner · 3 min read

What is String Template in Kotlin: Simple Explanation and Example

In Kotlin, a string template allows you to insert variables or expressions directly inside a string using the $ symbol. This makes building strings easier and more readable without needing extra concatenation.
⚙️

How It Works

Think of a string template like a sentence where you can easily drop in names or numbers without breaking the flow. Instead of writing a long sentence and then adding pieces together, Kotlin lets you write the sentence with placeholders that get replaced by actual values.

For example, if you want to say "Hello, John!" but the name changes, you can write "Hello, $name!" and Kotlin will swap $name with the real name. This works for simple variables or even more complex expressions inside curly braces.

💻

Example

This example shows how to use string templates to include variables and expressions inside a string.

kotlin
fun main() {
    val name = "Alice"
    val age = 25
    println("Hello, $name! You are $age years old.")
    println("Next year, you will be ${age + 1} years old.")
}
Output
Hello, Alice! You are 25 years old. Next year, you will be 26 years old.
🎯

When to Use

Use string templates whenever you need to create strings that include changing values like user names, numbers, or results of calculations. They make your code cleaner and easier to read compared to joining strings with plus signs.

Common real-life uses include generating messages, building URLs with parameters, or formatting output for reports and logs.

Key Points

  • String templates use $ to insert variables directly into strings.
  • Use curly braces {} to include expressions inside templates.
  • They improve readability and reduce errors compared to string concatenation.

Key Takeaways

String templates let you embed variables and expressions inside strings using $.
Use curly braces {} for complex expressions within string templates.
They make string building simpler and more readable than concatenation.
Ideal for dynamic messages, reports, and any string with changing data.