How do Factory and BuildFrom replace CanBuildFrom use cases in Scala 2.13?

Instruction: Explain the Scala 2.12-to-2.13 boundary and implement an explicit Factory that builds a collection of even integers. State whether ordinary inherited transformations preserve your custom collection type.

Context: Tests version-aware Scala collection construction, builder correctness, and the difference between explicit conversion and source-sensitive transformations.

Updated

Example answer

CanBuildFrom is part of the Scala 2.12-era collections design. In Scala 2.13, construction without an existing source uses Factory; operations whose result depends on the source collection can use BuildFrom. Do not paste a CanBuildFrom implementation into a Scala 2.13 or Scala 3 project and assume the old collection APIs remain unchanged.

This complete Scala 2.13 example explicitly builds an immutable collection of even integers. Filtering is visible in the factory's contract; it is not advertised as an ordinary map operation that silently discards results.

import scala.collection.Factory
import scala.collection.mutable

final class EvenNumbers private (private val values: Vector[Int])
    extends Iterable[Int] {
  override def iterator: Iterator[Int] = values.iterator
}

object EvenNumbers extends Factory[Int, EvenNumbers] {
  override def fromSpecific(source: IterableOnce[Int]): EvenNumbers = {
    val builder = newBuilder
    builder ++= source
    builder.result()
  }

  override def newBuilder: mutable.Builder[Int, EvenNumbers] =
    new mutable.Builder[Int, EvenNumbers] {
      private val values = Vector.newBuilder[Int]
      override def addOne(value: Int): this.type = {
        if (value % 2 == 0) values += value
        this
      }
      override def clear(): Unit = values.clear()
      override def result(): EvenNumbers = new EvenNumbers(values.result())
    }
}

object Demo extends App {
  val even = List(1, 2, 3, 4, 5, 6).to(EvenNumbers)
  assert(even.toList == List(2, 4, 6))
  assert(List(1, 3).to(EvenNumbers).isEmpty)
  assert(List(0, -2, -1).to(EvenNumbers).toList == List(0, -2))
}

For Scala 2.13, save as Demo.scala, compile with scalac Demo.scala, and run scala Demo. The custom factory makes conversion explicit. Inherited transformations return the collection types defined by Iterable; this example does not claim to preserve EvenNumbers through every transformation. A source-sensitive operation would need an appropriate BuildFrom design and its own type and behavior tests.

Sources

Scala 2.13 collection migration; Custom collection operations and builders.

Related Questions