Skip to content

Commit e5c550e

Browse files
committed
Preserve binary compatibility for Factory
Replace the trait Factory by an abstract type upper-bounded by CanBuildFrom, this way usages of CanBuildFrom can be replaced by Factory without breaking binary compatibility. This has the unfortunate consequence that all methods available on CanBuildFrom are still available on Factory when compiling under old Scala versions, but that seems like a price worth paying for BC.
1 parent e6ba9c9 commit e5c550e

File tree

2 files changed

+27
-37
lines changed

2 files changed

+27
-37
lines changed

compat/src/main/scala-2.11_2.12/scala/collection/compat/Factory.scala

Lines changed: 0 additions & 37 deletions
This file was deleted.

compat/src/main/scala-2.11_2.12/scala/collection/compat/PackageShared.scala

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,33 @@ import scala.{collection => c}
1010
private[compat] trait PackageShared {
1111
import CompatImpl._
1212

13+
/**
14+
* A factory that builds a collection of type `C` with elements of type `A`.
15+
*
16+
* @tparam A Type of elements (e.g. `Int`, `Boolean`, etc.)
17+
* @tparam C Type of collection (e.g. `List[Int]`, `TreeMap[Int, String]`, etc.)
18+
*/
19+
type Factory[-A, +C] <: CanBuildFrom[Nothing, A, C] // Ideally, this would be an opaque type
20+
21+
implicit class FactoryOps[-A, +C](private val factory: Factory[A, C]) {
22+
/**
23+
* @return A collection of type `C` containing the same elements
24+
* as the source collection `it`.
25+
* @param it Source collection
26+
*/
27+
def fromSpecific(it: TraversableOnce[A]): C = (factory() ++= it).result()
28+
29+
/** Get a Builder for the collection. For non-strict collection types this will use an intermediate buffer.
30+
* Building collections with `fromSpecific` is preferred because it can be lazy for lazy collections. */
31+
def newBuilder: m.Builder[A, C] = factory()
32+
}
33+
34+
implicit def fromCanBuildFrom[A, C](implicit cbf: CanBuildFrom[Nothing, A, C]): Factory[A, C] =
35+
cbf.asInstanceOf[Factory[A, C]]
36+
37+
implicit def fromCanBuildFromConversion[X, A, C](x: X)(implicit toCanBuildFrom: X => CanBuildFrom[Nothing, A, C]): Factory[A, C] =
38+
fromCanBuildFrom(toCanBuildFrom(x))
39+
1340
implicit def genericCompanionToCBF[A, CC[X] <: GenTraversable[X]](
1441
fact: GenericCompanion[CC]): CanBuildFrom[Any, A, CC[A]] =
1542
simpleCBF(fact.newBuilder[A])

0 commit comments

Comments
 (0)