Kotlin String Building
String building collects many pieces of text into one string inside a builder. The builder holds the growing text, and one final call turns it into a String.
Building in a loop with buildString
The block runs with a builder as its receiver, so append() calls inside it need no name. A dash is added before every number except the first.
fun main() {
val text = buildString {
for (n in 1..5) {
if (n > 1) {
append("-")
}
append(n * 2)
}
}
println(text)
}Using StringBuilder directly
A StringBuilder value is filled with append() calls that name it. The call toString() hands back the finished text, and its length can then be read.
fun main() {
val builder = StringBuilder()
builder.append("Order ")
builder.append(7)
builder.append(": ")
builder.append("tea")
val text = builder.toString()
println(text)
println(text.length)
}Starting with a capacity
A capacity is a starting size for the room the builder reserves. It changes nothing about the finished text.
fun main() {
val text = buildString(64) {
append("Report")
append(" ready")
}
println(text)
}Building a report line by line
The call appendLine() adds a line break after each piece. The last piece uses append() so the report ends without an extra break.
fun main() {
val report = buildString {
appendLine("Sales report")
appendLine("Tea: 12")
appendLine("Coffee: 9")
append("Total: 21")
}
println(report)
}Example
fun main() {
val names = listOf("Ada", "Grace", "Linus")
val scores = listOf(91, 87, 95)
val board = buildString {
appendLine("Leaderboard")
for (i in names.indices) {
append(names[i])
append(": ")
appendLine(scores[i])
}
append("Players: ")
append(names.size)
}
println(board)
}Key points
- Use buildString() to run a block that fills a builder and returns the finished String.
- Use append() to add a piece to the end of the builder, in call order.
- The append() call accepts values of many types, such as Int, and writes their text form.
- Use the StringBuilder class directly when the builder itself must be kept and passed around.
- Call toString() on a StringBuilder to take the finished text out of it.
- Give buildString() an initial capacity, such as buildString(64), to reserve room for the text ahead of time.
- Use appendLine() to add a piece plus a line break in one call.
In this example a leaderboard is assembled inside one buildString block. The heading goes in first, the loop appends one name and score per line, and a closing line adds the player count, so the whole board prints as a single string.
Note
A long text built in a loop stays inside one builder, instead of making a fresh string on every pass.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Kotlin Playground
Exercise
A buildString block appends "ab" first and "cd" second. What does printing the built string show?