Scala教程之:Option-Some-None

在java 8中,為了避免NullPointerException,引入了Option,在Scala中也有同樣的用法。他們就是Option, Some 和None.

其中Option是一個抽象類。

<code>sealed abstract class Option[+A] extends Product with Serializable 
/<code>

我們看下Some和None的定義:

<code>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")
}
/<code>

可以看到Some是一個繼承了Option的case class。 而None是一個繼承了Option[Nothing]的case object。

我們看下在程序中該怎麼使用他們。

Option和Some

<code>  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}")
/<code>

上面的例子中,我們定義了一個類型為String的Option,然後用Some給它賦了一個值。接下來我們調用Option的get方法來獲取這個String值。

下面是運行的結果:

<code>Step 1: How to use Option and Some - a basic example
Glazed Donut taste = Very Tasty
/<code>

這裡直接調用get會有問題,就是get出來的結果也可能是空的,這樣就不能避免NullPointerException的問題。

Option和None

下面我們看下None的用法:

<code>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")}")
/<code>

上面我們定義了一個Option,並給給他賦值None。在獲取值的時候,我們沒有調用get方法,相反我們使用的是getOrElse,如果值為空,則給他一個默認值。 下面是輸出結果:

<code>Step 2: How to use Option and None - a basic example
Glazed Donut name = Glazed Donut
/<code>

注意, None沒有get方法, 如果你像第一個例子一樣調用的話,會報錯:java.util.NoSuchElementException: None.get。

Option和模式匹配

上面的例子中我們使用了getOrElse來獲取值,還有一種方法叫做模式匹配:

<code>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!")
/<code>

這樣我們不管Option裡面到底有沒有值,都可以完成匹配。下面是輸出的結果。

<code>Step 3: How to use Pattern Matching with Option
No donut name was found!
/<code>

歡迎關注我的公眾號:程序那些事,更多精彩等著您!

更多內容請訪問:flydean的博客 flydean.com


Scala教程之:Option-Some-None


分享到:


相關文章: