How do you implement custom collection operations in Scala?
Instruction: Discuss the process of extending Scala collections with custom operations, including examples.
Updated
For an additional operation on existing collections, define an extension method rather than implementing a new collection hierarchy. Put the extension in a named scope and import it where needed. Scala 2.13 commonly uses an implicit class for the corresponding pattern; this example uses Scala 3 syntax. Extension methods
object IntStatistics {
extension (values: IterableOnce[Int]) {
def mean: Option[BigDecimal] = {
val iterator = values.iterator
var total = BigInt(0)
var count = BigInt(0)
while (iterator.hasNext) {
total += iterator.next()
count += 1
}
if (count == 0) None
else Some(BigDecimal(total) / BigDecimal(count))
}
}
}
@main def collectionOperationExample(): Unit = {
import IntStatistics.*
assert(List(1, 2, 3).mean.contains(BigDecimal(2)))
assert(List.empty[Int].mean.isEmpty)
assert(List(Int.MaxValue, Int.MaxValue).mean.contains(BigDecimal(Int.MaxValue)))
val input = Iterator(2, 4)
assert(input.mean.contains(BigDecimal(3)) && !input.hasNext)
}
The operation accepts finite input, traverses it once and returns None when a mean is undefined for an empty input. BigInt avoids fixed-width overflow in the sum and count; decimal division follows the BigDecimal math context, so a repeating fraction is rounded. One iterator and two accumulators do not imply constant bytes or constant-cost arithmetic because arbitrary-precision numbers can grow.
An iterator is consumed, whereas an ordinary reusable collection can produce another iterator. Specify those semantics, the empty case and numeric precision in the API contract. A real custom collection type additionally needs appropriate collection construction and transformation behavior; it is unnecessary just to add this calculation.