How to Use String Template in Kotlin: Simple Guide
string templates by placing a dollar sign $ before a variable name inside a string, like "Hello, $name". For expressions, wrap them in curly braces like "Sum is ${a + b}" to include the result directly in the string.Syntax
A string template in Kotlin allows you to insert variables or expressions inside a string easily. Use $variableName to insert a variable's value. For more complex expressions, use ${expression} inside the string.
This makes your code cleaner and easier to read compared to string concatenation.
val name = "Alice" val age = 25 val greeting = "Hello, $name! You are $age years old." val calculation = "Next year, you will be ${age + 1}."
Example
This example shows how to use string templates to include variables and expressions inside strings. It prints a greeting message and a calculation result.
fun main() {
val name = "Bob"
val score = 88
println("Player: $name")
println("Score: $score")
println("Next score will be ${score + 10}")
}Common Pitfalls
One common mistake is forgetting to use curly braces for expressions, which causes errors or unexpected output. Also, using $ without a valid variable name will cause a compile error.
Always use ${} when you want to insert an expression or when the variable name is followed by characters that could be part of the name.
val apples = 5 // Wrong: prints literal text instead of value val wrong = "I have $applesapples" // Right: use braces to separate variable name val right = "I have ${apples} apples"
Quick Reference
- $variable: Inserts the value of a variable.
- ${expression}: Inserts the result of an expression.
- Use curly braces
{}to avoid ambiguity. - Works only inside double-quoted strings
"".