— Kotlin, String Templates — 1 min read
String templates provide a convenient way to embed expressions inside string literals in Kotlin. They allow you to evaluate an expression inside a string literal and include its result as part of the string. This can be useful for generating dynamic strings on the fly or formatting data for display.
The syntax for string templates is simple. Just enclose the expression you want to evaluate inside curly braces within the string literal. For example:
1val name = "Alice"2println("Hello, $name!")
This will output:
1Hello, Alice!
You can also include more complex expressions inside the curly braces:
1val x = 102val y = 53println("$x + $y = ${x + y}")
This will output:
110 + 5 = 15
If you need to include a literal dollar sign ($) inside a string template, you can escape it with a backslash ():
1println("\$10")
This will output:
1$10
Kotlin also supports raw strings, which can be useful for including large blocks of text that may contain special characters without having to escape them manually. To define a raw string, use three double quotes (""") instead of just one:
1val rawString = """2 |First line3 |Second line4 |Third line5""".trimMargin()6
7println(rawString)
This will output:
1First line2Second line3Third line
Note the use of trimMargin()
to remove the leading pipe symbols that are automatically added to each line.
String templates are a powerful feature of Kotlin that make it easy to generate dynamic strings with embedded expressions. By enclosing expressions inside curly braces within a string literal, you can easily create formatted output for display or other purposes.