Strings and String Templates
Prerequisites: Basic types and type inference
A string is a piece of text in double quotes.
String templates
Put $name inside a string to insert a variable's value, or
${ ... } to insert the result of any expression:
fun main() {
val name = "Ada"
val age = 36
println("Hello, $name!")
println("Next year you'll be ${age + 1}.")
println("Your name has ${name.length} letters")
println("Price: \$5")
}
Hello, Ada!
Next year you'll be 37.
Your name has 3 letters
Price: $5
Templates convert any value to text for you. \$ prints a literal
dollar sign.
Joining with + also works, as long as the left side is a string:
fun main() {
val first = "Ada"
println(first + " Lovelace")
println("Age: " + 36)
}
Ada Lovelace
Age: 36
Templates are usually clearer than +, especially with several values.
Escape characters
\n— new line\t— tab\"— a double quote\\— a backslash
Raw strings
Triple quotes create a raw string: escape characters aren't
processed, and it can span several lines. trimIndent() removes the
common indentation:
fun main() {
val name = "Ada"
val message = """
Dear $name,
Thanks for signing up.
""".trimIndent()
println(message)
}
Dear Ada,
Thanks for signing up.
Templates still work inside raw strings.
Common mistakes
- Writing
"$name.length"and expecting the length — Kotlin insertsnameand then prints.lengthas text. Use"${name.length}". 36 + " years"— a number on the left can't be joined to a string with+. Use a template:"$age years".
Practice
Store a product name and a price, then print Coffee costs $3.5 using a
template.
Show solution
fun main() {
val product = "Coffee"
val price = 3.5
println("$product costs \$$price")
}
Coffee costs $3.5