Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
91: StringBuilder Usage in Kotlin
Imagine you're writing a grocery list on a whiteboard. When you remember you need eggs, you just walk up to the board and write "Eggs" at the bottom. You didn't have to erase the entire board, rewrite the milk, bread, and butter, and then finally add the eggs. That would be an exhausting way to shop.
In Kotlin, standard String objects are like pieces of paper that can't be erased. They are immutable. Every time you use the + operator to add a word to a string, Kotlin isn't actually adding to the existing text; it's creating a brand new piece of paper, copying everything from the old one over, and adding the new part. If you do this inside a loop a thousand times, you're creating a thousand temporary pieces of paper that the Garbage Collector eventually has to clean up. It's a massive waste of memory and CPU.
That's where StringBuilder comes in. It's your whiteboard. It provides a mutable buffer where you can add, remove, or change characters without recreating the entire object every single time.
Stopping the Memory Leak in Your Loops
I've seen a lot of junior devs write code like this when generating a formatted list of items. It looks clean, but it's a performance nightmare in production:
val users = listOf("Alice", "Bob", "Charlie", "Diana")
var report = ""
for (user in users) {
report += "User: $user\n" // This creates a new String object on every single iteration!
}
Instead, we use StringBuilder. You instantiate it, append your data, and then call toString() only once at the very end to "take a photo" of your whiteboard and turn it into a final, immutable string.
val users = listOf("Alice", "Bob", "Charlie", "Diana")
val reportBuilder = StringBuilder()
for (user in users) {
reportBuilder.append("User: ").append(user).append("\n")
}
val finalReport = reportBuilder.toString()
The Kotlin Way: buildString
While StringBuilder() is the standard approach, Kotlin provides a much more idiomatic helper function called buildString. It's essentially a wrapper that handles the creation and the toString() call for you, giving you a DSL-like experience.
I personally use this 90% of the time because it removes the boilerplate of managing the builder variable. Look at how much cleaner this is:
val users = listOf("Alice", "Bob", "Charlie", "Diana")
val finalReport = buildString {
for (user in users) {
append("User: ")
append(user)
append("\n")
}
}
Inside the buildString block, this refers to the StringBuilder object, so you can call append, insert, or delete directly.
Knowing Which Tool to Grab
Now, I don't want you to go overboard. You don't need a StringBuilder for every single string. If you're just joining two or three variables together in one line—like "Hello, $name!"—just use string templates. The Kotlin compiler is smart enough to optimize those simple cases for you.
Reach for StringBuilder or buildString specifically when:
- You are modifying a string inside a loop.
- You are building a large document or a complex piece of JSON/HTML manually.
- You need to perform complex manipulations, like inserting text into the middle of a long string using
insert().
📋 Practical Task
Building a Custom Transaction Receipt Generator
You need to create a function that generates a formatted receipt string from a list of purchase objects. Instead of using string concatenation, use buildString to ensure the process is memory-efficient.
Requirements:
- Define a data class
Purchase(val item: String, val price: Double). - Create a function
generateReceipt(purchases: List<Purchase>, customerName: String): String. - The receipt should start with "Customer: [name]" followed by a dashed line.
- Iterate through the purchases and append each item and price (e.g., "Apple: $1.50").
- Calculate the total price during the loop and append "Total: $[sum]" at the very bottom.
- Return the final string.
Example Output:
Customer: Jane Doe
-----------
Coffee: $3.50
Bagel: $4.00
-----------
Total: $7.50
There are no comments for now.