Skip to content

Add an empty operation to all collection instances #5813

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

Closed
Closed
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
11 changes: 11 additions & 0 deletions library/src/dotty/DottyPredef.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package dotty

import scala.forceInline
import scala.collection.generic.IsTraversableLike

object DottyPredef {

Expand Down Expand Up @@ -55,4 +56,14 @@ object DottyPredef {
* @group utilities
*/
@forceInline def valueOf[T](implicit vt: ValueOf[T]): T = vt.value

/**
* Add an `empty` operation to all collection instances, returning an empty collection
* of the same type.
*/
implicit class EmptyOperation[C](c: C)(implicit isTraversable: IsTraversableLike[C]) {
// Ideally we would use `withFilter`, but it is not defined on `GenTraversableLike`.
def empty: C = isTraversable.conversion(c).filter(_ => false)
}

}
40 changes: 40 additions & 0 deletions tests/pos/collectionsEmpty.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
object collectionsEmpty {

locally {
val xs1 = List(1, 2, 3)
val xs2 = xs1.empty
val xs3: List[Int] = xs2
}

locally {
val xs1 = Array(1, 2, 3)
val xs2 = xs1.empty
val xs3: Array[Int] = xs2
}

locally {
val xs1 = Set(1, 2, 3)
val xs2 = xs1.empty
val xs3: Set[Int] = xs2
}

locally {
val xs1 = "foo"
val xs2 = xs1.empty
val xs3: String = xs2
}

// Commented because there is no IsTraversableLike[Range] instance
// locally {
// val xs1 = 1 to 3
// val xs2 = xs1.empty
// val xs3: IndexedSeq[Int] = xs2
// }

locally {
val xs1 = Iterable(1, 2, 3)
val xs2 = xs1.empty
val xs3: Iterable[Int] = xs2
}

}