scala Option Some None
所属分类 scala
浏览量 650
Option是一个抽象类
None 和 Some 继承Option
sealed abstract class Option[+A]() extends scala.AnyRef with scala.Product with scala.Serializable {
final case class Some[+A](val value : A) extends scala.Option[A] with scala.Product with scala.Serializable {
case object None extends scala.Option[scala.Nothing] with scala.Product with scala.Serializable {
trait Option[T] {
def isDefined: Boolean
def get: T
def getOrElse(t: T): T
}
object OptionDemo {
def main(args: Array[String]) {
val map = Map("a" -> 1, "b" -> 2)
val value = map.get("a")
// class scala.Some
println(value.getClass)
println(value)
val value1: Option[Int] = map.get("a")
println(value1)
val value3: Int = value1.get
// int
println(value3.getClass)
// 1
println(value3)
if (value.isDefined) {
println(value.get)
} else {
println("null")
}
val value4 = map.get("a").getOrElse(null);
// class java.lang.Integer
println(value4.getClass)
println(value4)
val value5 = map.get("c")
// class scala.None$
println(value5.getClass)
// None
println(value5)
val value6 = map.get("c").getOrElse(null)
// println(value6.getClass)
// null
println(value6)
val value7 : Option[Int] = map.get("a")
val value8 : Some[Int] = null
val value9 : Any = null
}
}
isDefined — True if not empty
isEmpty — True if empty
nonEmpty — True if not empty
orElse — Evaluate and return alternate optional value if empty
getOrElse — Evaluate and return alternate value if empty
get — Return value, throw exception if empty
fold — Apply function on optional value, return default if empty
map — Apply a function on the optional value
flatMap — Same as map but function must return an optional value
foreach — Apply a procedure on option value
collect — Apply partial pattern match on optional value
filter — An optional value satisfies predicate
filterNot — An optional value doesn't satisfy predicate
exists — Apply predicate on optional value, or false if empty
forall — Apply predicate on optional value, or true if empty
contains — Checks if value equals optional value, or false if empty
toList — Unary list of optional value, otherwise the empty list
上一篇
下一篇
Scala中apply的用法
大数据工程师入门概述
scala 模式匹配
scala 类型系统
Scala 构造函数
scala range