scala学习笔记(2) -- Option Class

 Scala的Option class借鉴了sml里的option type。在sml里定义如下
Standard ML 代码
  1. datatype 'a option = NONE | SOME of 'a;  


相对应的,scala里是这么定义的

scala 代码
  1. sealed abstract class Option[+A] extends Product {   
  2.   def isEmpty: Boolean   
  3.   def isDefined: Boolean = !isEmpty   
  4.   def get: A   
  5.   def getOrElse[B >: A](default: => B): B =   
  6.     if (isEmpty) default else this.get   
  7.   def map[B](f: A => B): Option[B] =   
  8.     if (isEmpty) None else Some(f(this.get))   
  9.   def flatMap[B](f: A => Option[B]): Option[B] =   
  10.     if (isEmpty) None else f(this.get)   
  11.   def filter(p: A => Boolean): Option[A] =   
  12.     if (isEmpty || p(this.get)) this else None   
  13.   def foreach(f: A => Unit) {   
  14.     if (!isEmpty) f(this.get)   
  15.   }   
  16.   def orElse[B >: A](alternative: => Option[B]): Option[B] =   
  17.   def elements: Iterator[A] =   
  18.     if (isEmpty) Iterator.empty else Iterator.fromValues(this.get)   
  19.   def toList: List[A] =   
  20.     if (isEmpty) List() else List(this.get)   
  21. }   
  22.   
  23. final case class Some[+A](x: A) extends Option[A] {   
  24.   def isEmpty = false  
  25.   def get = x   
  26. }   
  27.   
  28. case object None extends Option[Nothing] {   
  29.   def isEmpty = true  
  30.   def get = throw new NoSuchElementException("None.get")   
  31. }  


比较重要的是Option里的函数,可以看到通过Option类型,有机地把“正常的”值和None结合了起来,由于Some(T)和None都是从 Option派生的,自然就支持了象map/filtering之类的函数式风格。更重要的一点,Some和None都是case class,从而可以将任何对象用在pattern matching里。如果再看一下scala的源代码中,在collection的实现中大量用到的就是Option对象,至于通过impllicit def在普通的对象和Option对象中转换的方法,以后会继续详细解释。

示例

scala 代码
  1. def getUser(user: User, isTrue: Boolean): Option[User] = {   
  2.  if (isTrue) Some(user)   
  3.             else None   
  4. }   
  5.   
  6. // pattern matching   
  7. getUser("chris") match {   
  8.   case Some(user) => user.modify()   
  9.   case None => error("not found")   
  10. }    
  11.   
  12. // default value   
  13. getUser("chris") getOrElse defaultUser   
  14.   
  15. // 通过Option和impllicit def定义复杂的操作   
  16. for( val x <- Some(3); val y <- Some(4) ) yield x * y // get Some(12)   
  17. for( val x:int <- Some(3); val y:int <- None ) yield x * y // get None   
  18. (for( val x:int <- Some(3); val y:int <- None ) yield x * y) getOrElse 9 // get 9   
  19.   

你可能感兴趣的:(scala,F#)