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
- scala自学日记(8)-Scala里面的Option
- scala自学日记(1)-Debain操作系统里面安装scala
- scala自学日记(5)-scala方法的定义方式
- scala的option
- scala自学日记(6)-数组的初始化以及循环
- Scala Option
- Scala Option
- scala自学日记(7)-Scala与Java在语法上的差异
- scala自学日记(2)-使用Scala解释器(interpreter)
- scala里面的zip
- scala里面的partition
- Scala里面的break
- scala自学日记(4)-万物皆对象
- scala的option和some
- scala的option使用实例
- scala里面的抽象类
- 详解Scala的Option的模式匹配
- Scala中常见的容器 Option(选项)
- webgis本地部署之静态网页与动态网页的工作机制
- block
- ioctlsocket() 用法
- POJ 1125(Floyd)
- winform窗体显示自定义位置,任意位置,窗体显示在屏幕下方
- scala自学日记(8)-Scala里面的Option
- 六、树节点的获取
- HDU 3076 ssworld VS DDD 概率DP
- orcal 数据库 sql语句优化总结
- 编写高效的Android代码
- sql常用语句总结
- Vi中一些实用的命令(上)
- webgis本地部署之ReiserFS
- 禁用 aspx页面的客户端缓存