In this tutorial, you shall learn how to write multiline string, using triple quotes, and also use trimIndent() function to trim the indentation if any. We will go through examples for each of these scenarios.

Kotlin – Multiline string

To define a multiline string in Kotlin, you can write the multiple line string literal and enclose it in triple quotes.

If you would like to trim the indentation, then you can use String.trimIndent() function as well along with triple quotes. The trimIndent() function removes the leading whitespace from each line.

Examples

1. Multiline string using triple quotes

In the following program, we define a multiline string in str.

Main.kt

</>
Copy
fun main() {
    val str = """This is line1.
This is line2.
This is line3."""
    println(str)
}

Output

This is line1.
This is line2.
This is line3.

2. Trim indentation of multiline string

In the following program, we define a multiline string in str, but with indentation. Indentation is given to improve the readability. But for this indentation to not affect the actual string value, we call trimIndent() on the string.

Main.kt

</>
Copy
fun main() {
    var str = """
        This is line1.
        This is line2.
        This is line3.
    """.trimIndent()
    println(str)
}

Output

This is line1.
This is line2.
This is line3.

If we do not trim the indentation, the new lines and tab characters are preserved in the string literal.

Main.kt

</>
Copy
fun main() {
    var str = """
        This is line1.
        This is line2.
        This is line3.
    """
    println(str)
}

Output

        This is line1.
        This is line2.
        This is line3.
    

Conclusion

In this Kotlin Tutorial, we learned how to define a multiline string using triple quotes and String.trimIndent() function, with well detailed examples.