Scala: Boolean to Option

I have a Boolean and would like to avoid this pattern:

if (myBool) 
  Option(someResult) 
else 
  None

What I'd like to do is

myBool.toOption(someResult)

Any suggestions with a code example would be much appreciated.


Solution 1:

Scalaz has a way to do it with BooleanOps.option. That would allow you to write :

myBool.option(someResult)

If you don't want to add a Scalaz dependency, just add the following in your code :

implicit class RichBoolean(val b: Boolean) extends AnyVal {
  final def option[A](a: => A): Option[A] = if (b) Some(a) else None
}

Solution 2:

Starting Scala 2.13, Option has a when builder for this exact purpose:

Option.when(condition)(result)

For instance:

Option.when(true)(3)
// Option[Int] = Some(3)
Option.when(false)(3)
// Option[Int] = None

Also note Option.unless which promotes the opposite condition.

Solution 3:

Option().collect() is a good pattern for this kind of thing.

Option(myBool).collect { case true => someResult }

from the REPL:

scala> (Option(true).collect { case true => 3 }, Option(false).collect { case true => 3 })
res3: (Option[Int], Option[Int]) = (Some(3),None)