summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorPaul Phillips <paulp@improving.org>2009-06-24 04:52:10 +0000
committerPaul Phillips <paulp@improving.org>2009-06-24 04:52:10 +0000
commitecb80ebcc57ad826e50f4770ae23b1ce834aeff8 (patch)
tree2a2bad665e16d2d3e98f889ec1df4bed1e44bc96 /src
parent6060a2984382ae52374c8a656af29fe88ef1d359 (diff)
downloadscala-ecb80ebcc57ad826e50f4770ae23b1ce834aeff8.tar.gz
scala-ecb80ebcc57ad826e50f4770ae23b1ce834aeff8.tar.bz2
scala-ecb80ebcc57ad826e50f4770ae23b1ce834aeff8.zip
Some enhancements to Option to cover a variety ...
Some enhancements to Option to cover a variety of cases which have come up repeatedly: Option factory which translates null to None .orNull method on Options of nullable types filterMap implementation so Option[T].filterMap => Option[U]
Diffstat (limited to 'src')
-rw-r--r--src/library/scala/Option.scala33
1 files changed, 31 insertions, 2 deletions
diff --git a/src/library/scala/Option.scala b/src/library/scala/Option.scala
index 263c9dec37..e40fc22829 100644
--- a/src/library/scala/Option.scala
+++ b/src/library/scala/Option.scala
@@ -11,13 +11,33 @@
package scala
-
import Predef._
+import annotation.experimental
-object Option {
+object Option
+{
/** An implicit conversion that converts an option to an iterable value
*/
implicit def option2Iterable[A](xo: Option[A]): Iterable[A] = xo.toList
+
+ /** An Option factory which creates Some(value) if the argument is not null,
+ * and None if it is null.
+ *
+ * @param x the value
+ * @return Some(value) if value != null, None if value == null
+ */
+ @experimental
+ def apply[A](x: A): Option[A] = if (x == null) None else Some(x)
+
+ class NullableOption[A >: Null <: AnyRef](x: Option[A]) {
+ /** The option's value if it is nonempty, or <code>null</code> if it is empty.
+ * The use of null of course is discouraged, but code written to use Options
+ * often must interface with code which expects and returns nulls.
+ */
+ @experimental
+ def orNull: A = if (x.isEmpty) null else x.get
+ }
+ implicit def option2NullableOption[A >: Null <: AnyRef](xo: Option[A]): NullableOption[A] = new NullableOption(xo)
}
/** This class represents optional values. Instances of <code>Option</code>
@@ -92,6 +112,15 @@ sealed abstract class Option[+A] extends Product {
if (!isEmpty) f(this.get)
}
+ /** If the given partial function <code>pf</code> is defined for the
+ * option's value, apply it to the value. Otherwise, None.
+ *
+ * @param pf the partial function.
+ */
+ @experimental
+ def filterMap[B](pf: PartialFunction[Any, B]): Option[B] =
+ if (!isEmpty && pf.isDefinedAt(this.get)) Some(pf(this.get)) else None
+
/** If the option is nonempty return it,
* otherwise return the result of evaluating an alternative expression.
* @param alternative the alternative expression.