scala的Option


當一個函數既要返回對象,又要返回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( )的方法,如果有數據,返回get里面的方法,如果沒有數據就返回默認的數值。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM