Skip to Content
Course content

91: StringBuilder Usage in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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

Rating
0 0

There are no comments for now.

to be the first to leave a comment.