scala学习手记19 - Option类型
2016-06-23 22:34
393 查看
看到Option类型就知道这本教材应该要说那个了。
使用过guava后,应该知道guava中的Optional类的作用是什么。算了找下原始文档好了:
scala中Option类的作用和Guava的Optional的意义是一致的。它们的意义在于两点:
增强null值的可读性,表达“我就是希望没有结果”的 意愿;
出于代码可用性考虑,强迫开发者主动检查对象的值是否为null。
看个例子:
代码中的commentonPractice()也许会返回一个字符串,也许什么都不会返回。在这个方法里使用了Some[T]和None实例分别应对了可能出现的两种情形。Some[T]和None都是Option[T]的子类。先看一下执行结果:
将类型显式声明为Option[String],Scala会强制我们检查实例的不存在。如此一来,就不太可能因为没有检查null引用而抛出NullPointerException。调用返回Option[T]的getOrElse()方法,可以主动的应对结果不存在(None)的情形。
就这样。
########
使用过guava后,应该知道guava中的Optional类的作用是什么。算了找下原始文档好了:
Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."
一句话,Guava中的Optional的作用是避免直接使用null。scala中Option类的作用和Guava的Optional的意义是一致的。它们的意义在于两点:
增强null值的可读性,表达“我就是希望没有结果”的 意愿;
出于代码可用性考虑,强迫开发者主动检查对象的值是否为null。
看个例子:
def commentOnPractice(input: String) = { //rather than returning null if (input == "test") Some("good") else None } for (input <- Set("test", "hack")) { val comment = commentOnPractice(input) println("input " + input + " comment " + comment.getOrElse("Found no comments")) }
代码中的commentonPractice()也许会返回一个字符串,也许什么都不会返回。在这个方法里使用了Some[T]和None实例分别应对了可能出现的两种情形。Some[T]和None都是Option[T]的子类。先看一下执行结果:
将类型显式声明为Option[String],Scala会强制我们检查实例的不存在。如此一来,就不太可能因为没有检查null引用而抛出NullPointerException。调用返回Option[T]的getOrElse()方法,可以主动的应对结果不存在(None)的情形。
就这样。
########
相关文章推荐
- 查看linux库文件32位还是64位
- 中国企业云操作系统的出路会是OpenStack吗?
- nginx信息功能启用
- nginx虚拟主机别名配置
- linux重点总结
- linux内核之页高速缓存
- 每天一个Linux命令(08)--cp命令
- shell脚本基本应用(三)特殊的Shell变量
- linux上进程状态查询
- linux如何查看一个进程的堆栈
- LINUX 下gets的 /r问题 北师大OJ Number theory
- 理解 Glance - 每天5分钟玩转 OpenStack(20)
- Centos6.8 64位编译安装PF_RING心得和总结
- LNMP环境搭建之--YUM仓库
- 解决:tomcat部署时deploy location不能显示加载后的路径【转载
- tomcat+eclipse web应用开发环境配置
- Docker学习笔记-数据卷、数据卷容器
- Docker学习笔记-数据卷、数据卷容器
- Docker学习笔记-数据卷、数据卷容器
- Apache Commons CLI官方文档翻译 —— 快速构建命令行启动模式