30

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?

dbc
  • 104,963
  • 20
  • 228
  • 340
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449

6 Answers6

46

How about

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

This expresses the intent clearly and is straight forward.

Walter Chang
  • 11,547
  • 2
  • 47
  • 36
28

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

marconi
  • 381
  • 3
  • 2
  • That's the way I go usually. I just can't understand by this answer is not accepted as the right one. – Boris Nov 05 '20 at 08:41
16

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

Some(2) exists (_ == 2)
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
7
val opt = Some("oxbow")
opt match {
  case Some("lakes") => //Doing something
  case _ => //If it doesn't match
}
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
3

You can use for-comprehension as well:

for {val v <- opt if v == "lakes"}
  // do smth with v
Alexander Azarov
  • 12,971
  • 2
  • 50
  • 54
-1

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
}
Jostein Stuhaug
  • 1,095
  • 10
  • 7
  • This does not test against the value - only that it is present. The reason I want to avoid a `match` is that this consequently results in the `else` logic residing in multiple places (i.e. the `case None` and if the value is not the desired one) – oxbow_lakes Oct 23 '09 at 15:34