summaryrefslogtreecommitdiff
path: root/src/library/scala/Option.scala
blob: c19748c87535a96c49b3b84adbbfa4581063d594 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2002-2004, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |                                         **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
** $Id:Option.scala 5359 2005-12-16 16:33:49 +0100 (Fri, 16 Dec 2005) dubochet $
\*                                                                      */

package scala;

import Predef._;


/** This class represents optional values. Instances of <code>Option</code>
 *  are either instances of case class <code>Some</code> or it is case
 *  object <code>None</code>.
 *
 *  @author  Martin Odersky
 *  @author  Matthias Zenger
 *  @version 1.0, 16/07/2003
 */
trait Option[+A] extends Iterable[A] {

  def isEmpty: Boolean = this match {
    case None => true
    case _ => false
  }

  def get: A = this match {
    case None => error("None.get")
    case Some(x) => x
  }

  def get[B >: A](default: B): B = this match {
    case None => default
    case Some(x) => x
  }

  def map[B](f: A => B): Option[B] = this match {
    case None => None
    case Some(x) => Some(f(x))
  }

  def flatMap[B](f: A => Option[B]): Option[B] = this match {
    case None => None
    case Some(x) => f(x)
  }

  def filter(p: A => Boolean): Option[A] = this match {
    case None => None
    case Some(x) => if (p(x)) Some(x) else None
  }

  override def foreach(f: A => Unit): Unit = this match {
    case None => ()
    case Some(x) => f(x)
  }

  def elements: Iterator[A] = this match {
    case None => Iterator.empty
    case Some(x) => Iterator.fromValues(x)
  }

  def toList: List[A] = this match {
    case None => List()
    case Some(x) => List(x)
  }

}