Scala Builders
A builder is a helper that collects pieces one by one and then freezes them into a finished collection. It is the mutable workbench behind an immutable result.
ListBuffer collects pieces with +=
Each += adds one number to the buffer. Calling toList freezes the pieces into a list.
@main def main(): Unit =
val buf = scala.collection.mutable.ListBuffer[Int]()
buf += 1
buf += 2
buf += 3
println(buf.toList)A list builder takes single pieces and whole lists
The += step adds one piece, and ++= adds a whole list. Calling result freezes everything into one list.
@main def main(): Unit =
val b = List.newBuilder[Int]
b += 1
b ++= List(2, 3)
println(b.result())StringBuilder collects text pieces
Each append adds one piece of text. Calling toString freezes the pieces into one string.
@main def main(): Unit =
val sb = new scala.collection.mutable.StringBuilder()
sb.append("hi")
sb.append(" ")
sb.append("there")
println(sb.toString)Example
@main def main(): Unit =
val buf = scala.collection.mutable.ListBuffer[Int]()
for n <- List(1, 2, 3, 4, 5, 6) do
if n % 2 == 0 then buf += n * n
println(buf.toList)
println(buf.size)Key points
- Builder: a builder collects pieces, and one final step turns them into a collection.
- Add: += adds one piece to a builder.
- Bulk: ++= adds every piece from another collection at once.
- Result: result or toList freezes the pieces into a finished list.
- ListBuffer: ListBuffer is the builder for lists, and it also offers toList.
In this example, the loop walks the numbers from 1 to 6 and adds the square of each even number to the buffer. The buffer then freezes into a list of three squares, and its size confirms that only the even numbers were kept.
Note
a builder itself changes as pieces arrive, while the list it produces does not.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
What does calling toList on a ListBuffer give you?