Skip to content
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

Add Array.from extension for scala 2.11 and 2.12 #658

Merged
merged 3 commits into from
Sep 17, 2024
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
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
Loading