Kotlin String Templates
A string template places a value inside a string at a marked spot. The mark is a dollar sign written before a name or before a pair of braces.
A name inside a greeting
The dollar sign and the name form one spot inside the text. The print fills the spot with the stored name.
fun main() {
val name = "Ana"
println("Hello, $name")
}A sum inside braces
Braces hold the sum a + b inside the string. The sum is worked out first, and its result takes the spot.
fun main() {
val a = 4
val b = 5
println("The sum is ${a + b}")
}A template in the middle of a sentence
The spot sits between plain words in this sentence. The words around it print exactly as written.
fun main() {
val city = "Paris"
println("The train to $city leaves at noon")
}Two spots in one string
This string holds two name spots in one line. Each spot is filled with its own stored value.
fun main() {
val name = "Ana"
val score = 42
println("$name scored $score points")
}Example
fun main() {
val name = "Bo"
val score = 17
println("Player $name")
println("$name scored ${score + 3} points")
}Key points
- Use $ with a name inside a string to place the value of that name in the text.
- Braces after a dollar sign hold a whole expression inside a string.
- The expression inside braces is worked out before the string prints.
- One string can hold several template spots.
In this example, name holds Bo and score holds 17. The first print fills the name spot and shows Player Bo. The second print fills the name spot, works out score + 3 inside the braces, and shows Bo scored 20 points.
Note
A template spot can sit anywhere in a string, at the start, in the middle, or at the end.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A program sets score to 17 and prints "Score: ${score + 3}". What prints?