在java 8中,为了避免NullPointerException,引入了Option,在Scala中也有同样的用法。他们就是Option, Some 和None.
其中Option是一个抽象类。
sealed abstract class Option[+A] extends Product with Serializable
我们看下Some和None的定义:
final case class Some[+A](@deprecatedName('x, "2.12.0") value: A) extends Option[A] {
def isEmpty = false
def get = value
@deprecated("Use .value instead.", "2.12.0") def x: A = value
}
/** This case object represents non-existent values.
*
* @author Martin Odersky
* @since 1.0
*/
@SerialVersionUID(5066590221178148012L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}
println("Step 1: How to use Option and Some - a basic example")
val glazedDonutTaste: Option[String] = Some("Very Tasty")
println(s"Glazed Donut taste = ${glazedDonutTaste.get}")
println("\nStep 2: How to use Option and None - a basic example")
val glazedDonutName: Option[String] = None
println(s"Glazed Donut name = ${glazedDonutName.getOrElse("Glazed Donut")}")
println("\nStep 3: How to use Pattern Matching with Option")
glazedDonutName match {
case Some(name) => println(s"Received donut name = $name")
case None => println(s"No donut name was found!")
这样我们不管Option里面到底有没有值,都可以完成匹配。下面是输出的结果。
Step 3: How to use Pattern Matching with Option
No donut name was found!