为了让所有的东西都是对象的目标更加一致,也为了遵循函数式编程的习惯。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.")
}
}
}
请关注作者公众号;