爲了讓所有的東西都是對象的目標更加一致,也爲了遵循函數式編程的習慣。Scala鼓勵你在變量和函數返回值可能不會引用任何值的時候使用Option類型。Scala的Option類型可以避免NullPointerException情況,因此,Scala應用推薦使用Option類型來代表一些可選值。使用Option類型,讀者一眼就可以看出這種類型的值可能爲None。
如果沒有值的時候使用None,這是Option的一個子類。 如果有值使用Some來包含這個值,Some也是Option的之類。
-
Option[T]
Option存在的意義, 就是爲了在代碼中註明, 讓大家一看就知道: "這個東西可能是空的! 你們用的時候給我小心點" 這樣的暗示 。有了這個暗示, 你可就不能隨意取出option裏面的東西了, 警醒你每次使用, 都要先判斷. isEmpty 或是 nonEmpty。
Option[T] 是一個類型爲 T 的可選值的容器: 如果值存在, Option[T] 就是一個 Some[T] ,如果不存在, Option[T] 就是對象 None 。
-
for循環
case class A(a: Int, b: Int) {
override def toString: String = a.toString + ": " + b.toString
}
object NullValue {
def main(args: Array[String]): Unit = {
var map1: Map[Int, A] = Map()
map1 += (1 -> A(1, 1))
map1 += (2 -> A(2, 2))
map1 += (3 -> A(3, 3))
map1 += (4 -> A(4, 4))
val result: Option[A] = map1.get(1)
result.foreach(println(_)) //當做容器使用,用for循環遍歷其中的元素;
}
}
-
map操作
在函數式編程語言中有一個核心的概念之一就是轉換,所以大部分支持函數式編程語言都支持一種叫做map的動作。
case class A(a: Int, b: Int) {
override def toString: String = a.toString + ": " + b.toString
}
object NullValue {
def main(args: Array[String]): Unit = {
var map1: Map[Int, A] = Map()
map1 += (1 -> A(11, 12))
map1 += (2 -> A(21, 22))
map1 += (3 -> A(31, 32))
map1 += (4 -> A(41, 42))
val result: Option[A] = map1.get(1)
result.map(_.b).map(_ + 100).foreach(println(_))
}
}
-
getOrElse()
case class A(a: Int, b: Int) {
override def toString: String = a.toString + ": " + b.toString
}
object NullValue {
def main(args: Array[String]): Unit = {
val a: Option[Int] = Some(2)
val b: Option[Int] = None
println(a.getOrElse(100000))
println(b.getOrElse(300000))
}
}
結果:
2
300000
-
isEmpty()
case class A(a: Int, b: Int) {
override def toString: String = a.toString + ": " + b.toString
}
object NullValue {
def main(args: Array[String]): Unit = {
val a: Option[Int] = Some(2)
val b: Option[Int] = None
println(a.isEmpty)
println(b.isEmpty)
}
}
結果:
false
true
-
Some的解釋
Class Some[A]
represents existing values of type A
Some[A] some是一定有值的, some.get獲取值;
如果沒有值, 會報異常. Predef.NoSuchElementException if the option is empty.
-
應用
case class A(a: Int, b: Int) {
override def toString: String = a.toString + ": " + b.toString
}
object NullValue {
def main(args: Array[String]): Unit = {
var map1: Map[Int, A] = Map()
map1 += (1 -> A(11, 12))
map1 += (2 -> A(21, 22))
map1 += (3 -> A(31, 32))
map1 += (4 -> A(41, 42))
matchFun(3, 4, map1) //72
matchFun(1, 5, map1) //value1: 11
matchFun(6, 7, map1) //default.
matchFun(5, 4, map1) //value2: 41
}
def matchFun(key1: Int, key2: Int, map: Map[Int, A]): Unit = {
(map.get(key1), map.get(key2)) match {
case (Some(value1), Some(value2)) => println(value1.a + value2.a)
case (None, Some(value2)) => println("value2: " + value2.a)
case (Some(value1), None) => println("value1: " + value1.a)
case _ => println("default.")
}
}
}