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
时间: 2024-10-07 22:06:51