🏎️ · Strings & string templates

1 min read Β· Updated on by

Read on to discover different string literals, string templates, and how to deal with whitespace.

First, learn about escaped strings, multiline strings, and especially about string templates, which make writing toString() methods a breeze (among many other things). Make special note of the fact that you can compute entire expressions inside string templates. For example, this is valid code:


//sampleStart
fun main() {
    fun isOdd(it: Int): Boolean = it % 2 == 1
    val numbers = (1..100)
    // We'll learn about function references (i.e. ::) in a bit
    println("Sum of odd numbers <= 100 is ${numbers.filter(::isOdd).sum()}")
}
//sampleEnd

This might seem difficult to read due to the way code gets highlighted in the Kotlin Playground, but the IDE does a much better job:

The string template example from above, but rendered inside an IDE, where the color scheme makes it easy to distinguish evaluated expressions from the rest of the string.

You can also use the handy library functions trimIndent and trimMargin to format multiline strings in accordance with the surrounding code.

If you want, replace the trimIndent call below with a trimMargin call taking "#" as the prefix value, so the resulting string doesn't contain the prefix character. Run the example to verify your solution.


import org.junit.Assert
import org.junit.Test

class Test {
    @Test(timeout = 1000)
    fun testTrimMargin() {
        Assert.assertEquals(
                "The margin prefix shouldn't be present in the resulting string",
                """
    			#question = "$question"
    			#answer = $answer
                """.trimMargin("#"),
                tripleQuotedString
        )
    }
}
//sampleStart
const val question = "life, the universe, and everything"
const val answer = 42

val tripleQuotedString = """
    #question = "$question"
    #answer = $answer
""".trimIndent()
//sampleEnd

Multiline strings are not only useful for strings spanning multiple lines, but also for creating regex patterns, because you don’t need to escape a backslash with a backslash.

The following pattern matches a date in the format 13.06.1992 (two digits, a dot, two digits, a dot, four digits):


//sampleStart
"""\d{2}\.\d{2}\.\d{4}"""
//sampleEnd

Compare that with:


//sampleStart
"\\d{2}\\.\\d{2}\\.\\d{4}"
//sampleEnd

God forbid you need to match an actual \, in which case you need 4 backslashes when using regular strings.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer