I’ve been using this pattern in the past:
class Acc[A]:
private val elems = List.newBuilder[A]
def += (x: A): Unit = elems += x
def snapshot: List[A] = elems.result()
val acc = Acc[Int]()
acc += 1
acc += 2
assert(acc.snapshot == List(1, 2))
acc += 3
assert(acc.snapshot == List(1, 2, 3))
It used to be explicitly allowed (I believe the staircase book mentioned it), but at some point, the documentation changed. Now, ReusableBuilder states: “In general no method other than clear() may be called after result() . It is up to subclasses to implement and to document other allowed sequences of operations”, and ListBuffer is silent (actually, List.newBuilder does not even state that is uses ListBuffer).
So, is the pattern still valid, and if so, could the documentation be improved to reflect it?