How to Use Multiline String in Kotlin: Syntax and Examples
In Kotlin, you can create a multiline string using
""" triple quotes. This allows you to write text across multiple lines without needing escape characters for newlines or quotes.Syntax
A multiline string in Kotlin is enclosed within triple double quotes """. Inside these quotes, you can write text on multiple lines exactly as you want it to appear. Leading whitespace can be trimmed using the trimMargin() function with a margin prefix.
kotlin
val multilineString = """ This is a multiline string in Kotlin. It preserves line breaks. """
Example
This example shows how to declare a multiline string and print it. It demonstrates that line breaks and spaces are kept as written inside the triple quotes.
kotlin
fun main() {
val poem = """
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.
""".trimIndent()
println(poem)
}Output
Roses are red,
Violets are blue,
Kotlin is fun,
And so are you.
Common Pitfalls
One common mistake is forgetting to use trimIndent() or trimMargin(), which can cause unwanted leading spaces in the output. Also, using regular double quotes " for multiline text will cause errors or require escape characters.
kotlin
fun main() {
// Wrong: Using regular quotes for multiline string
// val text = "This is line 1
// This is line 2" // This causes error
// Right: Use triple quotes
val text = """
This is line 1
This is line 2
""".trimIndent()
println(text)
}Output
This is line 1
This is line 2
Quick Reference
| Feature | Description | Example |
|---|---|---|
| Triple quotes | Enclose multiline text | """Your text here""" |
| Preserves line breaks | Keeps text formatting as is | Line1\nLine2 inside triple quotes |
| trimIndent() | Removes common leading whitespace | """ text """.trimIndent() |
| trimMargin() | Removes margin prefix from lines | """ |text """.trimMargin() |
Key Takeaways
Use triple quotes
""" to create multiline strings in Kotlin.Multiline strings keep line breaks and spaces exactly as typed.
Use
trimIndent() or trimMargin() to clean up leading spaces.Regular double quotes cannot hold multiline text without escapes.
Multiline strings are useful for writing formatted text or code snippets.