當一個函數既要返回對象,又要返回null的時候,使用Option[]
http://www.runoob.com/scala/scala-options.html
Option是scala的選項,用來表示一個鍵是可選的(有值或者無值),比如判斷一個map是否有值,可以直接使用get(xxx) ,返回的就是Option[String]
Option[]有兩個衍生值,一個是Some[],一個是None
final case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
def get = x
}
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
}
實際上他們就是對isEmpty和get進行了分別的設置。
一般在獲取出來的時候使用switch方法
def show(x: Option[String]) = x match {
case Some(s) => s
case None => "?"
}
Option有getOrElse(