A better way to test the value of an Option?

守給你的承諾、 提交于 2019-12-13 12:53:16

问题


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?


回答1:


How about

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

This expresses the intent clearly and is straight forward.




回答2:


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




回答3:


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

Some(2) exists (_ == 2)



回答4:


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



回答5:


You can use for-comprehension as well:

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



回答6:


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
}


来源:https://stackoverflow.com/questions/1611872/a-better-way-to-test-the-value-of-an-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!