Question

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?

Was it helpful?

Solution

How about

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

This expresses the intent clearly and is straight forward.

OTHER TIPS

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
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top