Raw and Multiline Strings

Triple-Quoted Strings

Example

A raw string uses """. It can span several lines and does not process escapes like \n. trimIndent() removes the common leading spaces.

fun main() {
    val message = """
        Your OTP is 482913.
        Do not share it with anyone.
        - Team Careeroza
    """.trimIndent()
    println(message)

    val path = """C:\Users\asha\notes.txt"""   // no need to escape backslashes
    println(path)
}

Output

Your OTP is 482913.
Do not share it with anyone.
- Team Careeroza
C:\Users\asha\notes.txt

trimMargin and Templates

Example

trimMargin() removes everything up to and including a | on each line. Templates still work in raw strings.

fun main() {
    val name = "Kiran"
    val amount = 750
    val sms = """
        |Dear $name,
        |₹$amount has been credited to your account.
        |Balance updated.
    """.trimMargin()
    println(sms)
}

Output

Dear Kiran,
₹750 has been credited to your account.
Balance updated.

Tip: Raw strings are perfect for JSON samples, SQL queries and regular expressions in tests.