scala自学日记(8)-Scala里面的Option

来源:互联网 发布:淘宝助理如何加水印 编辑:程序博客网 时间:2024/04/30 20:22
今天看到一段代码.如下:

package com.scala.demo/** Illustrate the use of pattern matching in Scala. */object patterns {    /** We need an abstract base class for trees. Subclasses with    *  the 'case' modifier can be used in pattern matching expressions    *  to deconstruct trees.    */  abstract class Tree  case class Branch(left: Tree, right: Tree) extends Tree  case class Leaf(x: Int) extends Tree  /** Case classes have an implicit constructor methods which allows    *  to create objects withouth the 'new' keyword. It saves some typing    *  and makes code clearer.    */  val tree1 = Branch(Branch(Leaf(1), Leaf(2)), Branch(Leaf(3), Leaf(4)))  /** Return the sum of numbers found in leaves.    *  'match' is a generalization of 'switch' in C-like languages    *    *  Patterns consist of case class constructors (which can    *  be nested), and lower case variables which are    *  bound to the values with which the class has been constructed.    */  def sumLeaves(t: Tree): Int = t match {    case Branch(l, r) => sumLeaves(l) + sumLeaves(r)    case Leaf(x) => x  }  /** This illustrates the use of Option types. Since the    *  method is not known in advance to find 'x', the    *  return type is an Option. Options have two possible    *  values, either 'Some' or 'None'. It is a type-safe    *  way around 'null' values.    */  def find[A, B](it: Iterator[(A, B)], x: A): Option[B] = {    var result: Option[B] = None    while (it.hasNext && result == None) {      val Pair(x1, y) = it.next      if (x == x1) result = Some(y)    }    result  }  def printFinds[A](xs: List[(A, String)], x: A) =    find(xs.iterator, x) match {      case Some(y) => println(y)      case None => println("no match")    }  def main(args: Array[String]) {    println("sum of leafs=" + sumLeaves(tree1))    printFinds(List((3, "three"), (4, "four")), 4)  }}

里面出现了Option[T],很是让我迷惑,这个到底是个什么类型的方法????

但是查阅了一番之后发现,Option[T]其实代表的是一个数据,但是和java里面的数据有点不同的是,Option[T]代表的数据里面不仅含有数据,还含有一个None,其实就是Null,

文章原话如下:

Scala 提供了一种普通的函数方法,打破了这一僵局。在某些方面,Option 类型或 Option[T],并不重视描述。它是一个具有两个子类 Some[T] 和 None 的泛型类,用来表示 “无值” 的可能性,而不需要语言类型系统大费周折地支持这个概念。实际上,使用 Option[T] 类型可以使问题更加清晰

注意:Option[T]里面的数据写法是Some(2)而不是2

原文地址:http://blog.sina.com.cn/s/blog_68af3f090100qkt8.html