Skip to content
DeveloperMemos

String Templates in Kotlin

Kotlin, String Templates1 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.

Syntax

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 = 10
2val y = 5
3println("$x + $y = ${x + y}")

This will output:

110 + 5 = 15

Escaping

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

Raw Strings

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 line
3 |Second line
4 |Third line
5""".trimMargin()
6
7println(rawString)

This will output:

1First line
2Second line
3Third 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.