getOrElse
代替// 源码
/** Class `Some[A]` represents existing values of type
* `A`.
*
* @author Martin Odersky
* @version 1.0, 16/07/2003
*/
@SerialVersionUID(1234815782226070388L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
final case class Some[+A](x: A) extends Option[A] {
def isEmpty = false
def get = x
}
// 源码
/** This case object represents non-existent values.
*
* @author Martin Odersky
* @version 1.0, 16/07/2003
*/
@SerialVersionUID(5066590221178148012L) // value computed by serialver for 2.11.2, annotation added in 2.11.4
case object None extends Option[Nothing] {
def isEmpty = true
def get = throw new NoSuchElementException("None.get")
示例
object TestOption {
def main(args: Array[String]) {
val map = Map("a" -> 1, "b" -> 2)
val value: Option[Int] = map.get("b")
val v1 =value match {
case Some(i) => i
case None => 0
}
println(v1)
//更好的方式
val v2 = map.getOrElse("c", 0)
println(v2)
}
# 输出
2
0