测试期权价值的更好方法?
我经常发现自己使用某种类型 T
的 Option[T]
并希望根据某个值测试该选项的值。例如:
val opt = Some("oxbow")
if (opt.isDefined && opt.get == "lakes")
//do something
以下代码是等效的,并且删除了测试选项值的存在的要求
if (opt.map(_ == "lakes").getOrElse(false))
//do something
但是,这对我来说似乎不太可读。其他可能性是:
if (opt.filter(_ == "lakes").isDefined)
if (opt.find(_ == "lakes").isDefined) //uses implicit conversion to Iterable
但我认为这些都没有清楚地表达意图,这会更好:
if (opt.isDefinedAnd(_ == "lakes"))
有没有人有更好的方法来进行此测试?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
怎么样
这句话表达的意图很明确,也很直接。
How about
This expresses the intent clearly and is straight forward.
对于 Scala 2.11,您可以使用
Some(foo).contains(bar)
For Scala 2.11, you can use
Some(foo).contains(bar)
Walter Chang FTW,但这是另一个尴尬的选择:
Walter Chang FTW, but here's another awkward alternative:
您也可以使用 for 理解:
You can use for-comprehension as well:
我认为也可以使用模式匹配。这样你就可以直接提取有趣的值:
I think pattern matching could also be used. That way you extract the interesting value directly: