Skip to content
Tutorials Center
My learning

Topics

Lesson 91 of 134 ยท Text, Files and Time

StringBuilder and buildString

Build strings efficiently in Kotlin: StringBuilder append, insert, delete and reverse, the buildString function, appendLine, Appendable, joinTo, and when concatenation is fine.

A Kotlin String is immutable: once created, its characters never change. Every operation that seems to modify a string, like +, replace or uppercase, returns a new string. For a handful of operations that is perfectly fine. When you assemble a large string piece by piece, for example a report with thousands of lines, or an HTML page, a CSV file, a log message built in a loop, creating a new string for every piece wastes time and memory.

The tool for that job is StringBuilder, a mutable sequence of characters that grows in place. Kotlin also adds buildString, a small function that makes using it pleasant. This lesson covers what StringBuilder can do, how buildString and appendLine work, how to write functions that accept any text destination with Appendable, and how to decide between a builder, a template and joinToString. It follows Strings and String Templates and Formatting.

Why immutable strings need a builder

Consider building a string by repeating += in a loop. Each iteration creates a brand-new string and copies everything built so far. The total copying grows with the square of the result length:

Kotlin How much copying += really does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Building 1,000 characters one at a time copies about 500,000 characters with +=. The builder appends in place, copying each character about once (it sometimes grows its internal buffer, doubling the space, which keeps the average cost small). At 100,000 characters the difference is no longer a curiosity but seconds of work.

flowchart LR
    subgraph S["text += piece"]
        A1["x"] --> A2["xx (new)"] --> A3["xxx (new)"] --> A4["xxxx (new)"]
    end
    subgraph B["builder.append(piece)"]
        B1["buffer: x"] --> B2["buffer: xx"] --> B3["buffer: xxx"] --> B4["buffer: xxxx"]
    end

Concatenation allocates a new string at every step; a builder keeps one growing buffer and produces the string once at the end.

Do not rewrite every + into a builder. The compiler turns a single expression like "Hello, " + name + "!" or a template "Hello, $name!" into efficient code on its own. A builder pays off when you add pieces in a loop or over many statements.

The StringBuilder toolbox

StringBuilder comes from Java's java.lang, but Kotlin makes it available in all code without an import and adds some extensions. Most methods return the builder itself, so calls chain:

Kotlin append, insert, delete, replace and reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Indexes work like they do for strings: they start at 0, and ranges such as deleteRange(0, 3) or replace(0, 4, ...) include the start and exclude the end. Going out of range throws IndexOutOfBoundsException.

Common members, grouped by purpose:

Purpose Members
Add append(x), insert(index, x), appendLine(x), appendRange(csq, start, end), appendCodePoint(cp)
Remove deleteAt(i), deleteRange(from, to), clear(), setLength(n)
Change set(i, c) (the [i] = c form), replace(from, to, str), reverse()
Read length, get(i), substring(from, to), indexOf, lastIndexOf, contains, isEmpty()
Capacity capacity(), ensureCapacity(n), StringBuilder(initialCapacity)
Finish toString()

A builder is not a String. Compare content with toString(): two builders with the same text are not equal under ==, because StringBuilder does not override equals.

Kotlin A StringBuilder is not a String

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

buildString

Creating a builder, appending and calling toString() is a recurring pattern, so Kotlin wraps it in buildString. Its lambda runs with the builder as this, and the result is the finished String:

Kotlin buildString and appendLine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Inside the lambda you call the builder's members without a prefix, so the code reads like a script that writes text. buildString is an inline function (see Inline Functions), so using it costs no extra object. You may pass a capacity hint, buildString(1024) { ... }, if you know roughly how big the result will be.

appendLine appends the text and a line feed (\n). It is available for StringBuilder and for any Appendable. Use it instead of append("...\n"): the intent is clearer and a lone appendLine() produces an empty line.

Building structured text

Builders shine for output formats. Here is a CSV writer that handles quoting, with the loop logic in one place:

Kotlin A small CSV writer with buildString

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The second row shows why a builder helps: a field that contains a comma or quote needs escaping, and branching code reads better as statements than as one huge template.

Appendable: writing to any destination

StringBuilder implements the interface Appendable (as do Writer, System.out wrappers and others). A function that takes an Appendable can write into a builder, a file or a network stream without changing code:

Kotlin One function, any destination

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

joinTo is the sibling of joinToString that appends into an existing destination instead of creating a new string, which saves a copy. If you only need the separators and a final String, joinToString is simpler.

Choosing the right tool

Situation Use
A few values in a sentence A template: "$name is $age"
A list with separators joinToString
A loop with branching or several statements buildString
Many appends across several functions Pass one StringBuilder (or Appendable) around
Formatted numbers String.format or "%.2f".format(x) (see String Templates and Formatting)
Text edited in place (reverse, insert, delete) StringBuilder

Other things to know

  • Thread safety: StringBuilder is not synchronized. Do not share one between threads. StringBuffer is the synchronized Java relative, but it is rarely needed; build per thread and combine the results.
  • Characters outside the BMP: length counts UTF-16 units. An emoji uses two, so appendCodePoint(0x1F600) raises length by 2. reverse() treats surrogate pairs correctly, but indexes do not know about visible characters.
  • Capacity: the builder doubles its buffer when it fills. Passing an initial capacity helps if you know the size; it is a hint, not a limit.
  • Finish with toString(): the builder keeps a mutable buffer, so convert it to a String once you are done and hand out that, not the builder.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is += in a loop slow for large strings?

    Strings are immutable, so s += x produces a fresh String each time. The total number of copied characters grows with the square of the final length.
  2. 2. What does buildString { ... } return?

    buildString creates a StringBuilder, runs the lambda with it as the receiver and returns the result of toString().
  3. 3. What is the value of StringBuilder("x") == StringBuilder("x")?

    StringBuilder uses identity equality. Compare builders with toString() or compareTo.
  4. 4. What does sb.deleteRange(0, 3) remove?

    The end index is exclusive, so three characters from index 0 are removed.
  5. 5. What is Appendable good for?

    Appendable is the shared interface of text destinations. A function taking it works with StringBuilder, Writer and more.

Summary

  • Strings are immutable; repeated += in a loop copies the growing text each time.
  • StringBuilder is a mutable buffer with append, insert, deleteRange, deleteAt, replace, reverse, setLength and clear.
  • buildString { } creates a builder, runs your lambda on it and returns the String; appendLine adds text and a newline.
  • Two builders with the same text are not ==; compare their toString().
  • Write output functions against Appendable, and use joinTo to append joined lists into one.
  • Templates and joinToString are better for small or list-shaped output; use a builder for loops and structured output.

Next: Introduction to Coroutines