简体   繁体   English

测试期权价值的更好方法是什么?

[英]A better way to test the value of an Option?

I often find myself with an Option[T] for some type T and wish to test the value of the option against some value. 对于某些类型的T ,我经常发现自己有一个Option[T] ,并且希望根据某个值来测试该选项的值。 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? 有没有人有更好的方法来做这个测试?

How about 怎么样

if (opt == Some("lakes"))

This expresses the intent clearly and is straight forward. 这清楚地表达了意图并且是直截了当的。

对于Scala 2.11,您可以使用Some(foo).contains(bar)

Walter Chang FTW,但这是另一个尴尬的选择:

Some(2) exists (_ == 2)
val opt = Some("oxbow")
opt match {
  case Some("lakes") => //Doing something
  case _ => //If it doesn't match
}

You can use for-comprehension as well: 您也可以使用for-understanding:

for {val v <- opt if v == "lakes"}
  // do smth with v

I think pattern matching could also be used. 我认为也可以使用模式匹配。 That way you extract the interesting value directly: 这样你直接提取有趣的值:

val opt = Some("oxbow")
opt match {
  case Some(value) => println(value) //Doing something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM