Strings and templates

Kotlin · Essentials · 8 min

Text handling is everywhere, and string templates make it concise and readable.

Kotlin strings are immutable sequences of characters. String templates embed values: "Hello, $name" for a simple variable, "Total: ${price * qty}" for any expression.

Raw strings use triple quotes. They can span lines and contain backslashes and quotes without escaping, which suits regular expressions, JSON and SQL. Use trimIndent() to remove the common leading indentation, or trimMargin() with a | margin marker. Kotlin 2.2 adds multi-dollar interpolation: $$"""{"price": "$5", "item": "$$item"}""" treats a single $ as a literal and needs $$ to interpolate.

Useful functions:

  • length, uppercase(), lowercase(), trim(), padStart(5, '0').
  • contains, startsWith, endsWith, indexOf, substring, replace.
  • split(","), lines(), joinToString(", ") on collections.
  • toInt() throws on bad input; toIntOrNull() returns null instead.
  • isBlank(), isNotEmpty(), ifBlank { "default" }.
  • Indexing s[0], first(), last(), take(3), drop(1).

== compares contents (it calls equals); === checks reference identity, which you rarely want for strings.

Use buildString { append(...) } or StringBuilder when assembling text in a loop. "%.2f".format(x) formats numbers like Java's String.format.

Example

fun main() {
    val name = "Ada"
    val items = listOf("pen", "ink")
    println("Hello, $name! You have ${items.size} items.") // Hello, Ada! You have 2 items.

    val json = """
        {"user": "$name"}
    """.trimIndent()
    println(json)                              // {"user": "Ada"}

    println("  hi  ".trim().uppercase())       // HI
    println("7".padStart(3, '0'))              // 007
    println("12x".toIntOrNull() ?: -1)         // -1
    println("a,b,c".split(",").joinToString(" | ")) // a | b | c
    println("%.2f".format(3.14159))            // 3.14

    val report = buildString {
        for (i in 1..3) append(i).append(';')
    }
    println(report)                            // 1;2;3;
}

Remember

  • $name and ${expr} interpolate values
  • Triple-quoted raw strings with trimIndent() for multiline text
  • == compares contents; === compares references
  • Use toIntOrNull() for safe parsing

Check yourself

  1. What does "Sum: ${1 + 2}" evaluate to?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: kotlinlang.org/docs/strings.html

Builds on

Unlocks

Nothing builds on this yet.