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

发布于 2024-08-08 05:21:21 字数 621 浏览 7 评论 0原文

我经常发现自己使用某种类型 TOption[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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

木格 2024-08-15 05:21:21

怎么样

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

这句话表达的意图很明确,也很直接。

How about

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

This expresses the intent clearly and is straight forward.

奈何桥上唱咆哮 2024-08-15 05:21:21

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

For Scala 2.11, you can use Some(foo).contains(bar)

独木成林 2024-08-15 05:21:21

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

Some(2) exists (_ == 2)

Walter Chang FTW, but here's another awkward alternative:

Some(2) exists (_ == 2)
锦爱 2024-08-15 05:21:21
val opt = Some("oxbow")
opt match {
  case Some("lakes") => //Doing something
  case _ => //If it doesn't match
}
val opt = Some("oxbow")
opt match {
  case Some("lakes") => //Doing something
  case _ => //If it doesn't match
}
作业与我同在 2024-08-15 05:21:21

您也可以使用 for 理解:

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

You can use for-comprehension as well:

for {val v <- opt if v == "lakes"}
  // do smth with v
旧夏天 2024-08-15 05:21:21

我认为也可以使用模式匹配。这样你就可以直接提取有趣的值:

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

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文