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

Scala的Option[T]是一个表示可能包含或不包含值的数据类型,不同于Java中的Null。Option有两个子类Some[T]和None,用于更清晰地处理可能不存在的值。使用Some(2)表示包含值2的Option实例。
摘要由CSDN通过智能技术生成
今天看到一段代码.如下:

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值