14

What's an easier/cleaner way to do this?

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

I've tried

o.getOrElse(null) == 4

but that feels wrong, since in the isEmpty case, you end up testing null against the other side... which could itself be null. I need it to be if opt is defined && opt.get == whatever. I feel like some method on Option should just take a function, and I could do it like so:

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

and it would apply the function only if o.isDefined.

Trenton
  • 11,678
  • 10
  • 56
  • 60

6 Answers6

23

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

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

There is also a predicate version of this:

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

Only use the predicate version if contains is not strong enough.

Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
10

You could also use:

if (o == Some(4)) //do something
oxbow_lakes
  • 133,303
  • 56
  • 317
  • 449
7

This seems reasonably clean to me:

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

If you want, you could even add an implicit conversion to add a convenience method for this:

implicit def richOption[A](o: Option[A]) = new {
  def test(p: A => Boolean): Boolean = o.map(p).getOrElse(false)
}
David Winslow
  • 8,472
  • 1
  • 31
  • 27
  • What is the purpose of the '==' after the 4? – James Black Nov 24 '09 at 20:17
  • "`4==`" is a function that tests for equality with 4 – Steve Gilham Nov 24 '09 at 20:45
  • Scala sugar. 4== is treated as an anonymous function of one argument in this case. More clearly (but more verbosely) might be: `o.map(4.==)` or `o.map(_ == 4)` or `o.map(x => x == 4)`. Key point here is that whatever you pass to Option.map() is only evaluated on non-None Options. – overthink Nov 24 '09 at 20:50
5

How about this:

val o = Some(4)
o match {
  case Some(4) => true
  case _ => false
}
Randall Schulz
  • 26,420
  • 4
  • 61
  • 81
2

The following seems most intuitive to me, if you don't care about the object creation overhead.

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

Another unsuggested method

val o = Some(4)
val Some(x) = o; x==4 // Edit: will not compile of o = None
Mitch Blevins
  • 13,186
  • 3
  • 44
  • 32
1
o.map(_ == 4).getOrElse(false)
Synesso
  • 37,610
  • 35
  • 136
  • 207