Strings and Text
|
This section documents Kotlin 2.4.x on the JVM, as published at kotlinlang.org, which is the reference these pages are written and verified against. This content was generated with the assistance of AI and should be verified against kotlinlang.org before being relied on in production. This section’s bibliography lists the reference material consulted while preparing these pages. |
String in Kotlin is java.lang.String — there is no separate string type — so every method already known
from Java is available. Kotlin adds string templates and multi-line raw strings on top.
String Templates
A $name or ${expression} inside a string literal is replaced with the value’s string representation at
run time — Kotlin’s built-in equivalent of Java’s String.format/text-block interpolation, with no separate
formatting call needed for the common case:
val name = "Ada"
val age = 30
println("Hello, $name! You are $age years old.") // simple property reference
println("Next year you'll be ${age + 1}.") // arbitrary expression needs braces
println("Your name has ${name.length} letters.") // method/property calls need braces too
// a literal dollar sign, when not followed by an identifier, needs no escaping;
// to interpolate literally use ${'$'}
println("Price: ${'$'}9.99")
Raw (Triple-Quoted) Strings
A triple-quoted string spans multiple lines with no escape processing at all — ideal for regular expressions, file paths, or embedded snippets that would otherwise need heavy backslash-escaping:
val regex = """\d{3}-\d{4}""" // no need to escape the backslashes
val query = """
|SELECT id, name
|FROM customers
|WHERE active = true
""".trimMargin() // strips everything up to and including the leading "|"
val path = """C:\Users\ada\file.txt""" // no backslash-escaping needed
trimMargin() (default margin prefix |, or a custom one) and trimIndent() (strips the common leading
whitespace of every line) are the standard ways to keep a raw string’s source indentation without that
indentation leaking into the resulting value.
Common String Operations
Because String is java.lang.String, methods like .length, .substring(), .indexOf(), .replace(),
.split(), .trim(), and .toUpperCase()/.uppercase() all work as expected; Kotlin adds a large set of
extension functions on top (see Extension
Functions and Scope Functions) for common tasks that need a manual loop in Java:
val csv = "id,name,active"
val fields = csv.split(",") // List<String>: ["id", "name", "active"]
val padded = "7".padStart(3, '0') // "007"
val repeated = "ab".repeat(3) // "ababab"
val stripped = " hi ".trim() // "hi"
// building a string efficiently in a loop uses buildString { ... } (backed by a StringBuilder)
val joined = buildString {
for (i in 1..3) append(i).append(", ")
} // "1, 2, 3, "
// multiplatform-friendly comparison instead of Java's `.equalsIgnoreCase`
val same = "Kotlin".equals("KOTLIN", ignoreCase = true) // true
length is a property (str.length), not a method call, unlike Java’s str.length() — one of the small,
deliberate differences meant to make code read more like plain English.
Comparison to Java’s String
-
==compares structural equality forStringin Kotlin (it calls.equals()), unlike Java where==compares references — see Equality and Operator Overloading for the full rule and its===referential-equality counterpart. -
Kotlin’s
Stringis immutable, exactly like Java’s —StringBuilder(alsojava.lang.StringBuilderdirectly, or wrapped bybuildString { }) remains the tool for repeated concatenation in a loop. -
Text blocks (
"""…"""in Java 15+) and Kotlin’s triple-quoted strings look similar but differ: Kotlin’s strips no indentation automatically (you call.trimIndent()/.trimMargin()explicitly), whereas Java’s text blocks strip common leading whitespace by the language rules themselves.
See Also
-
Equality and Operator Overloading —
==vs.===for strings and everything else. -
Extension Functions and Scope Functions — how
String’s extension functions (like `.trim(),.padStart()) are themselves ordinary library code. -
Collections and Sequences —
.split()’s `Listresult and the functional operations available on it.
References
-
Kotlin stdlib —
kotlin.textpackage reference (trimMargin,trimIndent,padStart, and the rest of theStringextension functions).