kotlinbeginner

String Templates and Multiline Strings

Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.

kotlin
fun main() {
    val name = "Alice"
    val age = 30

    // Basic templates
    println("Hello, $name!")           // Hello, Alice!
    println("Age: ${age + 1}")          // Age: 31
    println("Name has ${name.length} chars") // Name has 5 chars

    // Raw strings (triple-quoted)
    val json = """
        {
            "name": "$name",
            "age": $age,
            "active": true
        }
    """.trimIndent()
    println(json)

    // trimMargin with custom prefix
    val sql = """
        |SELECT u.name, u.email
        |FROM users u
        |WHERE u.age > $age
        |ORDER BY u.name
    """.trimMargin()
    println(sql)

    // Multi-line with processing
    val csv = """
        name,age,email
        Alice,30,alice@test.com
        Bob,25,bob@test.com
    """.trimIndent()
        .lines()
        .drop(1) // skip header
        .map { it.split(",") }
        .map { (n, a, e) -> "$n ($a): $e" }
    println(csv)

    // Regex in raw strings (no escaping needed)
    val emailPattern = """[\w.+-]+@[\w-]+\.[\w.-]+""".toRegex()
    println(emailPattern.matches("test@example.com")) // true

    // String builder
    val report = buildString {
        appendLine("=== Report ===")
        appendLine("Name: $name")
        appendLine("Age: $age")
        append("Status: Active")
    }
    println(report)

    // Padding and formatting
    val items = listOf(
        Triple("Laptop", 999.99, 2),
        Triple("Mouse", 29.99, 5),
        Triple("Keyboard", 149.99, 3)
    )
    println("%-15s %10s %5s".format("Item", "Price", "Qty"))
    println("-".repeat(32))
    items.forEach { (item, price, qty) ->
        println("%-15s %10.2f %5d".format(item, price, qty))
    }

    // Repeat and transform
    val border = "─".repeat(40)
    println(border)
    println("Hello".padStart(20).padEnd(40))
    println(border)
}

Use Cases

  • Dynamic string construction and formatting
  • SQL and JSON template generation
  • Report and table formatting

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.