Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiom for Scala's Option when doing equality tests

Tags:

scala

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.

like image 987
Trenton Avatar asked Nov 24 '09 19:11

Trenton


2 Answers

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.

like image 74
Rok Kralj Avatar answered Oct 11 '22 19:10

Rok Kralj


How about this:

val o = Some(4)
o match {
  case Some(4) => true
  case _ => false
}
like image 23
Randall Schulz Avatar answered Oct 11 '22 19:10

Randall Schulz