String templates
- Kotlin course
- Beginner
- Lesson 31/116
- 5 min
Learn string templates with \$ and \${}.
String templates
In Kotlin, string templates let you embed a variable or expression inside a String. For a simple variable, the $ prefix is enough.
val name = "Alex"
println("Hello, $name") // Hello, AlexYou can embed several variables in the same String side by side. Spaces and punctuation stay as they are; only the identifier after $ is replaced by its value.
Templates are more readable than splitting and concatenating text, so they are common in Kotlin.
Embedding expressions with ${}
For a simple variable, $name is enough. But to embed an expression (operation, call) use ${}.
val a = 3
val b = 4
println("Sum: ${a + b}") // Sum: 7Inside the braces you can write any Kotlin expression: arithmetic, method call, comparison. The result is converted to a String and embedded.
$name.length does not work; $ only takes name. For the length, write ${name.length}.
Practice Write a greeting with a template
Write a fun main(). Assign "Alex" to val name. Print the template "Hello, $name!" with println.
Starter code
fun main() {
// Write the greeting
}Sample solution
fun main() {
val name = "Alex"
println("Hello, $name!")
}Expected output
Hello, Alex!
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the template results
| Term | Meaning |
|---|---|
"Hello, $name" |
Greeting |
"Age: $age" |
Age info |
"$a + $b" |
Two variables |
"Done." |
Fixed text |
2 What does "Hello, $name" print? (name = "Alex")
val name = "Alex"
println("Hello, $name")- Hello, $name
- Hello, name
- Hello, Alex Correct answer
- Error
Explanation: $name is replaced by the value: Hello, Alex.
3 Complete the expression template
val msg = "Sum: ____"
val msg = "Sum: ${a + b}"
Explanation: ${a + b} embeds the expression value into the String.