
1. Overview
In this article, we will learn to create a multiline string in Kotlin.
You can look into our Kotlin articles to know more about other topics.
Kotlin has two types of the string literal:
escaped
strings that may contain escaped characters (For example:val s = "Hello, world!\n"
). You can escape the characters in a conventional way, with a backslash (\
).raw
or multiline strings that can contain newlines and arbitrary text and do not support backslash escaping.
It is recommended to use the multiline strings rather than using \n
escape sequences into regular string literals.
2. Create multiline strings
A raw
string is delimited by a triple quote ("""
), contains no escaping and can contain newlines and any other characters.
For example, the following main method contains a raw
string.
fun main() { val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """ println(text) println("Done") }
If you notice, the above code introduces additional leading whitespace characters.
|Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) Done
2.1. Remove leading whitespace from multiline string
To remove leading whitespace from raw strings, you can use the trimMargin()
function:
fun main() { val text = """ |Tell me and I forget. |Teach me and I remember. |Involve me and I learn. |(Benjamin Franklin) """.trimMargin() println(text) println("Done") }
If you look at the output of the above main
method, the leading whitespaces are removed.
Tell me and I forget. Teach me and I remember. Involve me and I learn. (Benjamin Franklin) Done
By default, |
is used as the margin prefix to remove the whitespace characters. However, you can choose another character and pass it as a parameter, like trimMargin(">")
.
Loot at the below example that chooses ">"
as the margin prefix. This produces the same result as above.
fun main() { val text = """ >Tell me and I forget. >Teach me and I remember. >Involve me and I learn. >(Benjamin Franklin) """.trimMargin(">") println(text) println("Done") }
2.2. Escape dollar sign in a multiline string
You can escape the $
character in the raw text.
The raw
text doesn’t support backslash escaping. As discussed in this article, Kotlin interprets the $
as an identifier to insert values of variables or expressions in a String.
If you want to insert the $
as a character in a raw string, use the following syntax:
val price = """ ${'$'}20 """ println(price) // prints "$20"
In a escaped or single-line text, you can use backslash escaping:
val singleLineText = "\$" println(singleLineText) // prints "$"
3. Conclusion
To sum up, we have learned to create a multiline string in Kotlin.