summaryrefslogtreecommitdiff
path: root/src/library
diff options
context:
space:
mode:
authorPaul Phillips <paulp@improving.org>2010-02-04 20:21:44 +0000
committerPaul Phillips <paulp@improving.org>2010-02-04 20:21:44 +0000
commitbd3afbf36eb21fe5d03b024a7641860ac6cefe4c (patch)
tree1ca189def3a78cd97514a20982da0c145b7d662b /src/library
parenta572d2d56dcedb0bdf8a3d8f9628cb5e3dd6df22 (diff)
downloadscala-bd3afbf36eb21fe5d03b024a7641860ac6cefe4c.tar.gz
scala-bd3afbf36eb21fe5d03b024a7641860ac6cefe4c.tar.bz2
scala-bd3afbf36eb21fe5d03b024a7641860ac6cefe4c.zip
Made a whole WithFilter class for Option after ...
Made a whole WithFilter class for Option after discovering this bug: scala> def f(x: AnyRef) = for (p <- Option(x)) yield p f: (x: AnyRef)Option[AnyRef] scala> def f(x: AnyRef) = for (p <- Option(x) ; if true) yield p f: (x: AnyRef)Iterable[AnyRef] The for comprehension logic apparently prefers to convert Option to Iterable to get at the withFilter method over using Option's filter.
Diffstat (limited to 'src/library')
-rw-r--r--src/library/scala/Option.scala17
1 files changed, 17 insertions, 0 deletions
diff --git a/src/library/scala/Option.scala b/src/library/scala/Option.scala
index 17bb6d0148..3bebcedd20 100644
--- a/src/library/scala/Option.scala
+++ b/src/library/scala/Option.scala
@@ -35,6 +35,7 @@ object Option
* @version 1.1, 16/01/2007
*/
sealed abstract class Option[+A] extends Product {
+ self =>
/** True if the option is the <code>None</code> value, false otherwise.
*/
@@ -89,6 +90,22 @@ sealed abstract class Option[+A] extends Product {
def filter(p: A => Boolean): Option[A] =
if (isEmpty || p(this.get)) this else None
+ /** Necessary to keep Option from being implicitly converted to
+ * Iterable in for comprehensions.
+ */
+ def withFilter(p: A => Boolean): WithFilter = new WithFilter(p)
+
+ /** We need a whole WithFilter class to honor the "doesn't create a new
+ * collection" contract even though it seems unlikely to matter much in a
+ * collection with max size 1.
+ */
+ class WithFilter(p: A => Boolean) {
+ def map[B](f: A => B): Option[B] = self filter p map f
+ def flatMap[B](f: A => Option[B]): Option[B] = self filter p flatMap f
+ def foreach[U](f: A => U): Unit = self filter p foreach f
+ def withFilter(q: A => Boolean): WithFilter = new WithFilter(x => p(x) && q(x))
+ }
+
/** If the option is nonempty, p(value), otherwise false.
*
* @param p the predicate to test