A better way to test the value of an Option?

oxbow_lakes picture oxbow_lakes · Oct 23, 2009 · Viewed 15.2k times · Source

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?

Answer

Walter Chang picture Walter Chang · Oct 23, 2009

How about

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

This expresses the intent clearly and is straight forward.