option

Option (option) is used to represent a type value is optional (there is no value or values).

If present, Option [T] is Some [T], if not present, Option [T] is the object None

myMap a Key -Value is a type, but he's get () returns the Option class

1. 

object Test {
   def main(args: Array[String]) {
      val sites = Map("runoob" -> "www.runoob.com", "google" -> "www.google.com")
      println("runoob:"+sites.get("runoob"))
      println("baidu:"+sites.get("baidu"))

 }}
Test.main(Array())

runoob: Some (www.runoob.com)
baidu: None
defined object Test

  

2. Pattern Matching

object Test {
   def main(args: Array[String]) {
      val sites = Map("runoob" -> "www.runoob.com", "google" -> "www.google.com")
 
      println("runoob:"+show(sites.get("runoob")))
      println("baidu:"+show(sites.get("baidu")))


   def show(x:Option[String])=x match{
       case Some(s)=>s
       case None =>"?"
} 



}}
Test.main(Array())

runoob: www.runoob.com
baidu :?
defined object Test

  

3. getOrElse () method to obtain the tuple in presence or using its default value

object Test {
   def main(args: Array[String]) {

   val a:Option[Int]=Some(5)
   val b:Option[Int]=None


   println("a:"+a.getOrElse(0))
   println("b:"+b.getOrElse(10))




}}

Test.main(Array())

a:5
b:10
defined object Test

4. isEmpty () method

object Test {
   def main(args: Array[String]) {
      val a:Option[Int] = Some(5)
      val b:Option[Int] = None 
      
      println("a.isEmpty: " + a.isEmpty )
      println("b.isEmpty: " + b.isEmpty )
   }
}
Test.main(Array())


a.isEmpty: false
b.isEmpty: true
defined object Test

  

Guess you like

Origin www.cnblogs.com/hapyygril/p/11649735.html