Skip to content

Commit e566811

Browse files
authored
Add Array.from extension for scala 2.11 and 2.12 (#658)
1 parent 3fe1cb0 commit e566811

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

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

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,9 @@ private[compat] trait PackageShared {
272272
builder.result()
273273
}
274274

275+
implicit def toArrayExtensions(fact: Array.type): ArrayExtensions =
276+
new ArrayExtensions(fact)
277+
275278
implicit def toImmutableSortedMapExtensions(
276279
fact: i.SortedMap.type): ImmutableSortedMapExtensions =
277280
new ImmutableSortedMapExtensions(fact)
@@ -357,6 +360,14 @@ private[compat] trait PackageShared {
357360
new RandomExtensions(self)
358361
}
359362

363+
final class ArrayExtensions(private val fact: Array.type) extends AnyVal {
364+
def from[A: ClassTag](source: TraversableOnce[A]): Array[A] =
365+
source match {
366+
case it: Iterable[A] => it.toArray[A]
367+
case _ => source.toIterator.toArray[A]
368+
}
369+
}
370+
360371
class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal {
361372
def from[K: Ordering, V](source: TraversableOnce[(K, V)]): i.SortedMap[K, V] =
362373
build(i.SortedMap.newBuilder[K, V], source)

compat/src/test/scala/test/scala/collection/CollectionTest.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,9 @@ class CollectionTest {
5656
@Test
5757
def testFrom: Unit = {
5858
val xs = List(1, 2, 3)
59+
val a = Array.from(xs)
60+
val aT: Array[Int] = a
61+
assertTrue(Array(1, 2, 3).sameElements(a))
5962
val v = Vector.from(xs)
6063
val vT: Vector[Int] = v
6164
assertEquals(Vector(1, 2, 3), v)

0 commit comments

Comments
 (0)