开发者

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. 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 开发者_如何学JAVAa better way of doing this test?


How about

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

This expresses the intent clearly and is straight forward.


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


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

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 {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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜