Skip to content

Commit

Permalink
Add Array.from extension for scala 2.11 and 2.12 (#658)
Browse files Browse the repository at this point in the history
  • Loading branch information
RustedBones authored Sep 17, 2024
1 parent 3fe1cb0 commit e566811
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ private[compat] trait PackageShared {
builder.result()
}

implicit def toArrayExtensions(fact: Array.type): ArrayExtensions =
new ArrayExtensions(fact)

implicit def toImmutableSortedMapExtensions(
fact: i.SortedMap.type): ImmutableSortedMapExtensions =
new ImmutableSortedMapExtensions(fact)
Expand Down Expand Up @@ -357,6 +360,14 @@ private[compat] trait PackageShared {
new RandomExtensions(self)
}

final class ArrayExtensions(private val fact: Array.type) extends AnyVal {
def from[A: ClassTag](source: TraversableOnce[A]): Array[A] =
source match {
case it: Iterable[A] => it.toArray[A]
case _ => source.toIterator.toArray[A]
}
}

class ImmutableSortedMapExtensions(private val fact: i.SortedMap.type) extends AnyVal {
def from[K: Ordering, V](source: TraversableOnce[(K, V)]): i.SortedMap[K, V] =
build(i.SortedMap.newBuilder[K, V], source)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class CollectionTest {
@Test
def testFrom: Unit = {
val xs = List(1, 2, 3)
val a = Array.from(xs)
val aT: Array[Int] = a
assertTrue(Array(1, 2, 3).sameElements(a))
val v = Vector.from(xs)
val vT: Vector[Int] = v
assertEquals(Vector(1, 2, 3), v)
Expand Down

0 comments on commit e566811

Please sign in to comment.