Skip to content

Issue 337 factory.newBuilder should return new instances #338

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
version=1.5.1
align = more
docstrings = JavaDoc
assumeStandardLibraryStripMargin = true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,12 @@ private[compat] trait PackageShared {

implicit def genericCompanionToCBF[A, CC[X] <: GenTraversable[X]](
fact: GenericCompanion[CC]): CanBuildFrom[Any, A, CC[A]] = {
val builder: m.Builder[A, CC[A]] = fact match {
/* see https://github.com/scala/scala-library-compat/issues/337
`simpleCBF.apply` takes a by-name parameter and relies on
repeated references generating new builders, thus this expression
must be non-strict
*/
def builder: m.Builder[A, CC[A]] = fact match {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could probably optimise this so that it doesn't have to pattern match each time, and only does so once

case c.Seq | i.Seq => new IdentityPreservingBuilder[A, i.Seq](i.Seq.newBuilder[A])
case c.LinearSeq | i.LinearSeq =>
new IdentityPreservingBuilder[A, i.LinearSeq](i.LinearSeq.newBuilder[A])
Expand Down
14 changes: 14 additions & 0 deletions compat/src/test/scala/test/scala/collection/FactoryTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,19 @@ class FactoryTest {
val result = factory.fromSpecific(source)
Assert.assertEquals(1, counter) // One element has been evaluated because Stream is not lazy in its head
}
@Test
def factoriesAreReusable(): Unit = {
def generically[M[X] <: Iterable[X]](in: M[Int], factory: Factory[Int, M[Int]]): Unit = {
val l = Iterator(-3, -2, -1).to(factory)
val m = in.iterator.to(factory)
Assert.assertEquals(in, m)
}

generically[List](List(1, 2, 3), List)
generically[Seq](Seq(1, 2, 3), Seq)
generically[IndexedSeq](IndexedSeq(1, 2, 3), IndexedSeq)
generically[Vector](Vector(1, 2, 3), Vector)
generically[Set](Set(1, 2, 3), Set)
}

}