scala 测试期权价值的更好方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1611872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A better way to test the value of an Option?
提问by oxbow_lakes
I often find myself with an Option[T]for some type Tand wish to test the value of the option against some value. For example:
我经常发现自己使用了Option[T]某种类型,T并希望根据某个值测试该选项的值。例如:
val opt = Some("oxbow")
if (opt.isDefined && opt.get == "lakes")
//do something
The following code is equivalent and removes the requirement to test the existenceof 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?
有没有人有更好的方法来做这个测试?
回答by Walter Chang
How about
怎么样
if (opt == Some("lakes"))
This expresses the intent clearly and is straight forward.
这清楚地表达了意图并且直截了当。
回答by marconi
For Scala 2.11, you can use Some(foo).contains(bar)
对于 Scala 2.11,您可以使用 Some(foo).contains(bar)
回答by Daniel C. Sobral
Walter Chang FTW, but here's another awkward alternative:
Walter Chang FTW,但这是另一个尴尬的选择:
Some(2) exists (_ == 2)
回答by Ken Bloom
val opt = Some("oxbow")
opt match {
case Some("lakes") => //Doing something
case _ => //If it doesn't match
}
回答by Alexander Azarov
You can use for-comprehension as well:
您也可以使用 for-comprehension:
for {val v <- opt if v == "lakes"}
// do smth with v
回答by Jostein Stuhaug
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
}

