What is String Template in Kotlin: Simple Explanation and Example
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.
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.")
}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.