Idiom for Scala Option when running equality tests

What is a simple / cleaner way to do this?

val o = Some(4) if(o.isDefined) {o.get == 4} else { false } 

I tried

 o.getOrElse(null) == 4 

but this seems wrong, because in the case of isEmpty you end up checking zero against the other side ... which itself may be zero. I need this to be if opt is defined && & opt.get == anything. I feel that some method on Option should just take a function, and I could do it like this:

 o.test( (x) => x == 4 ) 

and this function will be applied only if o.isDefined.

+6
scala
source share
7 answers

This is the cleanest, most idiomatic way to do this.

 val o = Some(4) o.contains(4) // true o.contains(5) // false 

There is also a predicate version:

 val o = Some(4) o.exists(_ > 0) // true o.exists(_ > 100) // false 

Use only the predicate version if contains not strong enough.

+12
source share

You can also use:

 if (o == Some(4)) //do something 
+9
source share

This seems clean enough to me:

 o.map(4==).getOrElse(false) 

If you want, you can even add an implicit conversion to add a convenient method for this:

 implicit def richOption[A](o: Option[A]) = new { def test(p: A => Boolean): Boolean = o.map(p).getOrElse(false) } 
+7
source share

How about this:

 val o = Some(4) o match { case Some(4) => true case _ => false } 
+5
source share

The following seems most intuitive to me if you do not need the overhead of creating an object.

 val o = Some(4) Some(4) == o 

Another suggested method

 val o = Some(4) val Some(x) = o; x==4 // Edit: will not compile of o = None 
+2
source share
 o.map(_ == 4).getOrElse(false) 
+1
source share

Try the following:

 val o = Some(4) o.exists(4 == _) 
+1
source share

All Articles