Scala: Boolean to Option

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)

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
}

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.

Tags:

Scala