Skip to content

Commit

Permalink
Add an empty operation to all collection instances
Browse files Browse the repository at this point in the history
This will allow us to experiment with a different desugaring of `for`
expressions, as described in scala#2573.
  • Loading branch information
julienrf committed Jan 29, 2019
1 parent 190f34b commit 35e1cca
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
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
}

}

0 comments on commit 35e1cca

Please sign in to comment.