0
0
KotlinHow-ToBeginner · 3 min read

How to Use String Template in Kotlin: Simple Guide

In Kotlin, you use 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.

kotlin
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.

kotlin
fun main() {
    val name = "Bob"
    val score = 88
    println("Player: $name")
    println("Score: $score")
    println("Next score will be ${score + 10}")
}
Output
Player: Bob Score: 88 Next score will be 98
⚠️

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.

kotlin
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 "".

Key Takeaways

Use $variableName to insert variable values inside strings.
Wrap expressions in ${} to include their results in strings.
Always use curly braces when inserting expressions or to avoid ambiguity.
String templates work only inside double-quoted strings.
Avoid syntax errors by not placing $ before invalid names.