kotlinbeginner
String Templates and Multiline Strings
Format strings in Kotlin: templates, raw strings, trimMargin, trimIndent, and template processing.
kotlinPress ⌘/Ctrl + Shift + C to copy
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.
kotlinbeginner
String Processing Utilities
Common string operations in Kotlin: split, join, pad, replace, regex, and template processing.
Best for: CSV and delimited data parsing
#kotlin#strings
kotlinbeginner
Date and Time Operations in Kotlin
Work with dates and times using java.time: parsing, formatting, duration, period, and timezone handling.
Best for: Date formatting for user interfaces
#kotlin#datetime
javabeginner
Java String Formatting and Templates
String formatting techniques: printf, format, MessageFormat, StringJoiner, and text block interpolation.
Best for: Formatted log messages and reports
#java#string
kotlinbeginner
Null Safety — Elvis, Safe Call, and let
Master Kotlin null safety: safe calls, Elvis operator, let/also scoping, and smart casts.
Best for: Safe navigation through nullable chains
#kotlin#null-safety