Scala 學習筆記之集合(7) Option
阿新 • • 發佈:2017-06-29
bject fin pre object c cti abc collect 結果 ==
object CollectionDemo8 { def main(args: Array[String]): Unit = { //Option集合的使用,可以用來安全的判斷null或非null,放心使用,不會拋出空指針異常 val s: String = "abcd" val sp = Option(s) println(sp.isDefined) println(sp.isEmpty) if (sp == Some("abcd")) { println("Has value") } if (Option(null) == None) { println("Has no value") } println(List(1, 2, 3, 4, 5).headOption) println(List(1, 2, 3, 4, 5).find { x => x == 3 }) //Option集合提取值 println(Option("abc").fold("bcd")(x => x)) println(Option(null).fold("bcd")(x => x)) println(Option("abc").getOrElse("value")) println(Option(null).getOrElse("value")) println( Option("abc") match { case Some(x) => x case None => -1 }) } }
運行結果:
true
false
Has value
Has no value
Some(1)
Some(3)
abc
bcd
abc
value
abc
Scala 學習筆記之集合(7) Option