CodeBlanks Logo Icon CodeBlanks

String templates

Learn to embed variables in strings with \$ and \${}.

String templates: $ and ${}

In Kotlin you use the $ sign to embed a variable or expression inside a string. Writing $name inserts the value of the name variable.

For more complex expressions use ${...}: "Sum: ${a + b}". This feature is called a string template and is more readable than string concatenation.

val name = "Alex"
println("Hello $name")          // Hello Alex
println("Sum: ${2 + 3}")         // Sum: 5

Practice Greet the user

Write a fun main(). Inside it declare val name = "Alex". Print Hello $name with println.

Sample solution

Main.kt
fun main() {
    val name = "Alex"
    println("Hello $name")
}

Expected output

Hello Alex

Escaping the dollar sign

In a string template $ is always treated as a variable embed. To write a literal $, escape it with \$: println("Price: \$5") prints Price: $5.

You can also use ${'$'}. Both methods put a real dollar sign in the string safely. Without the escape, Kotlin looks for a variable name after $ and raises a compile error if it cannot find one.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this code print?

Main.kt
val name = "Alex"
println("Hello $name")
  • Hello Alex Correct answer
  • Hello $name
  • Hello val name
  • It throws an error

Explanation: $name is replaced by the value Alex.

2 Complete the expression

Question
println("Sum: ${____}")
Answer
println("Sum: ${a + b}")

Explanation: ${a + b} embeds the expression.

3 String templates: match the terms

Term Meaning
$ Variable embed
${} Expression embed
"..." String
println Output

All lessons in Beginner