Raphael Roth
Raphael Roth

Reputation: 27373

How to check whether two Options are both defined / undefined in scala

I want to check whether the "state" of two options are the same:

val a : Option[Double]= ??
val b : Option[Double]= ??

How can this be written in a nice way?

val sameState = (a.isDefined && b.isDefined) || (!a.isDefined && !b.isDefined)

So in words : If a is None and b is None it shoud return true, if a is Some and b is Some it should also return true, otherwise it should return false

My solution seems quite unscala-ish. I'm looing for something like:

val sameState = (a.definition == b.definition)

Edit : background:

I have a Seq[Option[_]] and want to split it into a Seq[Seq[Option[_]] depending on whether the "state" of consecutive elements changes as in Grouping list items by comparing them with their neighbors

Upvotes: 1

Views: 988

Answers (3)

simpadjo
simpadjo

Reputation: 4017

Maybe just a.isDefined == b.isDefined ?

Upvotes: 2

Puneeth Reddy V
Puneeth Reddy V

Reputation: 1568

You can try using match over the tuple of two option you are having. Something like this

def isBothDefined(a : Option[Double], b : Option[Double]) = (a,b) match{
  case (Some(x), Some(y)) => "Both defined"
  case (Some(x), None) => "b is not defined"
  case (None, Some(y)) => "a is not defined"
  case _ => "nither s defined"
}

Output

isBothDefined(Option.apply(1.0), Option.empty[Double])
res3: String = b is not defined

Upvotes: -1

Raphael Roth
Raphael Roth

Reputation: 27373

Just found an answer myself. There is also a size attribute on Option (being 1 for Some, 0 for None):

val sameState = (a.size == b.size)

Why this works? There is an implicit conversion from Option[A] to Iterable[A] called option2Iterable

Upvotes: 0

Related Questions