🧵 Kotlin – Strings: Templates, Methods, and Multiline Handling
🧲 Introduction – Why Learn Kotlin Strings?
Strings are everywhere—user input, logs, labels, and more. Kotlin takes string handling to the next level with powerful features like string templates, built-in methods, and multiline strings. These tools make Kotlin code concise, readable, and efficient for any kind of string manipulation.
🎯 In this guide, you’ll learn:
- How to declare and use strings in Kotlin
- Use of string templates for clean concatenation
- Most commonly used string methods
- How to write and format multiline strings
🔤 Kotlin String Basics
val name: String = "Kotlin"
println(name)
- Strings are objects of type
String. - You can use either explicit type declaration or type inference:
val greeting = "Hello, World!"
🧩 String Templates – Inline Variable & Expression Insertion
Kotlin supports string templates, which allow you to embed variables and expressions directly inside strings.
✅ Syntax:
val name = "Riya"
val age = 24
println("Name: $name, Age: $age")
🟢 Output:
Name: Riya, Age: 24
🧠 Embedding Expressions:
Use ${...} for expressions.
val x = 5
val y = 3
println("Sum: ${x + y}")
🟢 Output:
Sum: 8
🛠️ Commonly Used Kotlin String Methods
Kotlin provides a rich set of built-in string functions:
| Method | Description | Example |
|---|---|---|
length | Returns string length | "Kotlin".length → 6 |
uppercase() | Converts to uppercase | "kotlin".uppercase() → "KOTLIN" |
lowercase() | Converts to lowercase | "KOTLIN".lowercase() → "kotlin" |
substring(start, end) | Extracts substring | "Kotlin".substring(0, 3) → "Kot" |
contains("sub") | Checks if string contains substring | "Kotlin".contains("lin") → true |
startsWith("Ko") | Checks prefix | "Kotlin".startsWith("Ko") → true |
endsWith("in") | Checks suffix | "Kotlin".endsWith("in") → true |
replace("K", "J") | Replaces characters | "Kotlin".replace("K", "J") → "Jotlin" |
trim() | Removes whitespace | " hello ".trim() → "hello" |
🧾 Multiline Strings – Triple Quotes """..."""
Use triple quotes to create multiline strings without escape sequences.
val text = """
Kotlin is modern
Kotlin is powerful
Kotlin is concise
""".trimIndent()
println(text)
🟢 Output:
Kotlin is modern
Kotlin is powerful
Kotlin is concise
🧽 Optional Formatting Methods:
.trimIndent()– Removes leading whitespace from each line.trimMargin()– Removes custom margin prefix like|
val message = """
|Hello,
|Welcome to Kotlin!
""".trimMargin()
println(message)
🔄 String Concatenation in Kotlin
✅ Using + operator:
val firstName = "John"
val lastName = "Doe"
println(firstName + " " + lastName)
✅ Using string templates:
println("$firstName $lastName")
✔️ Templates are cleaner and preferred over + concatenation in Kotlin.
📦 Kotlin Raw Strings vs Escaped Strings
| Type | Syntax Example | Behavior |
|---|---|---|
| Escaped String | "Line1\nLine2" | Requires escape characters |
| Raw String | """Line1\nLine2""" | Treats as literal characters |
🚫 Common Mistakes with Strings
| ❌ Mistake | ✅ Correction |
|---|---|
Using + repeatedly for concatenation | Use string templates ("$a $b") |
Forgetting .trimIndent() in multiline | Text will include unwanted spaces |
| Null values without check | Use ?.length or safe string handling |
✅ Best Practices for Kotlin Strings
| Practice | Reason |
|---|---|
Prefer string templates over + | More readable and cleaner |
Use trimIndent() in triple-quoted text | Properly formats multiline content |
| Check nullability before operations | Prevents runtime crashes |
| Use built-in methods for transformations | Avoids manual string manipulation |
📌 Summary – Recap & Next Steps
Kotlin’s string features offer powerful formatting, built-in methods, and multiline flexibility that make it easier to handle text-based operations. String templates make your code shorter, safer, and more expressive.
🔍 Key Takeaways:
- Use
$variableand${expression}for string interpolation. - Triple quotes (
""") support multiline strings. - Built-in methods like
uppercase(),trim(),replace()simplify manipulation. trimIndent()andtrimMargin()help format raw strings.
⚙️ Practical Use:
Strings are central to Android UI, REST APIs, logs, and form inputs. Efficient string handling is critical in all Kotlin apps.
❓ FAQs – Kotlin Strings
❓ What are string templates in Kotlin?
✅ A way to embed variables and expressions inside strings using $variable or ${expression} syntax.
❓ How do you write multiline strings in Kotlin?
✅ Use triple quotes """ ... """ and optionally call .trimIndent() or .trimMargin() to format them.
❓ What’s the difference between raw and escaped strings?
✅ Escaped strings require characters like \n, while raw strings (with triple quotes) preserve literal formatting.
❓ How do you convert strings to uppercase or lowercase?
✅ Use uppercase() and lowercase() methods:
"hello".uppercase() // HELLO
❓ Can strings in Kotlin be null?
✅ Yes, use nullable types:
val name: String? = null
Always use safe calls like name?.length.
Share Now :
