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?