一种测试期权价值的更好方法? [英] A better way to test the value of an Option?
本文介绍了一种测试期权价值的更好方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我经常发现自己的Option[T]
类型为T
,并且希望针对某个值测试选项的值.例如:
I often find myself with an Option[T]
for some type T
and wish to test the value of the option against some value. For example:
val opt = Some("oxbow")
if (opt.isDefined && opt.get == "lakes")
//do something
以下代码是等效的,删除了测试选项值的存在性的要求
The following code is equivalent and removes the requirement to test the existence of the value of the option
if (opt.map(_ == "lakes").getOrElse(false))
//do something
但是,对于我来说,这似乎不太容易理解.其他可能性是:
However this seems less readable to me. Other possibilities are:
if (opt.filter(_ == "lakes").isDefined)
if (opt.find(_ == "lakes").isDefined) //uses implicit conversion to Iterable
但是我不认为这些意图能更好地表达意图:
But I don't think these clearly express the intent either which would be better as:
if (opt.isDefinedAnd(_ == "lakes"))
有人有更好的方法进行这项测试吗?
Has anyone got a better way of doing this test?
推荐答案
关于
if (opt == Some("lakes"))
这清楚地表达了意图,并且是直截了当的.
This expresses the intent clearly and is straight forward.
这篇关于一种测试期权价值的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文