天天看點

Scala之Option

推薦:部落客曆時三年傾注大量心血創作的《大資料平台架構與原型實作:資料中台建設實戰》一書已由知名IT圖書品牌電子工業出版社博文視點出版發行,真誠推薦給每一位讀者!點選《重磅推薦:建大資料平台太難了!給我發個工程原型吧!》了解圖書詳情,掃碼進入京東手機購書頁面!

Scala之Option

機場等飛機,繼續學習Scala~~ 本文原文出處: http://blog.csdn.net/bluishglc/article/details/51290759 嚴禁任何形式的轉載,否則将委托CSDN官方維護權益!

Option是一個很有意思的類,首先,這個類并不一個真正的集合類,因為它并沒有有繼承Traversable或Iterable。但是,它确實具有Iterable的所有操作,這意味着你完全可以把Option當成一個集合去使用,其中原因你應該可以猜的到,這顯然是隐式轉換在起作用。具體來說是Option的伴生對象中定義了一個隐式轉化函數option2Iterable, 你還記得隐式解析的作用域嗎?伴生對象也是編譯器針對類型進行隐式轉換解析時查找的作用域,也就是說:當你試圖把Option當成一個Iterable使用時,編譯器是在Option的伴生對象的option2Iterable方法上找到了這個隐式轉化聲明:

implicit def option2Iterable[A](xo: Option[A]): Iterable[A]

           

進而确認了從Option向Iterable的隐式轉化是定義好的。(至于另外的4個隐式轉換:by any2stringadd, by any2stringfmt, by any2ArrowAssoc, by any2Ensuring是發生在PreDef中的,這4個是面向全局的任何類型的隐式轉換。

其次,我們來看一下這個類兩個子類:

First, it is far more obvious to readers of code that a variable whose type

is Option[String] is an optional String than a variable of type String,

which may sometimes be null. But most importantly, that programming

error described earlier of using a variable that may be null without first

checking it for null becomes in Scala a type error. If a variable is of type

Option[String] and you try to use it as a String, your Scala program will

not compile.

  1. Option具有更直白的語義:它代表的值可能是一個具體的值,但也可能是空!
  2. 在Java裡判空是一個運作時的動作,是以經常會出現忘記判空導緻的空指針異常。但是在scala裡,由于Option的引入,在你試圖使用Option裡的值時,你必選做相應的類型轉換,否則就會出現編譯錯誤,這是引入Option另一個重要目的,在編譯期進行判空處理!

比如:當你聲明一個Option[String]變量時,從語義上你就已經告知了編譯器,包括讀者,這個變量可能是一個String也可能是空,但是在試圖實際讀取這個值時,你必須先進行類型轉換和判空處理,否則編譯就無法通過,這是使用Option的主要同目的。

Option在Scala裡被廣泛使用,主要有如下場景:

  • Using Option in method and constructor parameters
  • Using Option to initialize class fields (instead of using null)
  • Converting null results from other code (such as Java code) into an Option
  • Returning an Option from a method
  • Getting the value from an Option
  • Using Option with collections
  • Using Option with frameworks
  • Using Try/Success/Failure when you need the error message (Scala 2.10 and

    newer)

  • Using Either/Left/Right when you need the error message (pre-Scala 2.10)

其次,我們來看一下這個類兩個子類:

##Returning an Option from a method

def toInt(s: String): Option[Int] = {
	try {
		Some(Integer.parseInt(s.trim))
	} catch {
		case e: Exception => None
	}
}
           
scala> val x = toInt("1")
x: Option[Int] = Some(1)
scala> val x = toInt("foo")
x: Option[Int] = None 
           

##Getting the value from an Option

這裡有三個類子示範從一個Option裡提取值:

###Use getOrElse

scala> val x = toInt("1").getOrElse(0)
x: Int = 1
           

getOrElse:顧名思義,對于一個Option,如有它确實有值就傳回值,否則,也就是為空的話,給一個約定的值。

###Use foreach

由于是Option可以被隐式轉換為Iterable,這意味着你可以把它當成一個普通的集合那樣去使用,使用foreach去疊代一個Option就是非常典型的例子。

toInt("1").foreach{ i =>
	println(s"Got an int: $i")
}
           

###Use a match expression

toInt("1") match {
	case Some(i) => println(i)
	case None => println("That didn't work.")
}