Strings and String Templates

Article · 2:00

Interpolation, raw strings and why Kotlin strings never surprise you with mutation.

Kotlin strings are immutable, like Java's, and they support templates: a dollar sign followed by a name inserts that value, and a dollar sign followed by braces inserts the result of any expression. This replaces concatenation almost entirely, and it is both faster to read and harder to get wrong than gluing pieces together with plus signs.

Raw strings, delimited by three quote marks, span lines and perform no escaping at all. A Windows file path, a regular expression or a block of JSON can be pasted in exactly as it appears elsewhere, with no backslash doubling. The trimIndent function then strips the common leading whitespace, so a raw string can be indented to match the surrounding code without that indentation ending up in the value.

Comparison is worth stating explicitly because it differs from Java. In Kotlin, == calls equals, so it compares content. Reference identity is ===. This is the opposite default from Java and it is almost always what you want - comparing two strings with == does the sensible thing.

For building strings in a loop, use buildString or a StringBuilder rather than repeated concatenation. Each concatenation allocates a new string, so a loop over a thousand items allocates a thousand intermediates.

fun main() {
    val name = "Kotlin"
    val versions = listOf(1.9, 2.0)

    // Simple template, and an expression template
    println("$name has ${versions.size} versions listed")
    println("The latest is ${versions.maxOrNull()}")

    // A raw string: no escaping, spans lines, trimIndent removes the margin
    val json = """
        {
          "language": "$name",
          "path": "C:\Users\dev"
        }
    """.trimIndent()
    println(json)

    // == compares content, === compares identity
    val a = "hello"
    val b = "hel" + "lo"
    println(a == b)    // true
}

Discussion

No questions on this topic yet. Sign in to ask the first one.