Scala: Boolean to Option
ScalaScala Problem Overview
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.
Scala Solutions
Solution 1 - Scala
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 - Scala
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 - Scala
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)
Solution 4 - Scala
None of the other answers answer the question as stated! To get the exact semantics you specified use:
implicit class BoolToOption(val self: Boolean) extends AnyVal {
def toOption[A](value: => A): Option[A] =
if (self) Some(value) else None
}
You can then write
myBool.toOption(someResult)
eg:
scala> true.toOption("hi")
res5: Option[String] = Some(hi)
scala> false.toOption("hi")
res6: Option[String] = None
Solution 5 - Scala
If you don't mind someResult
being evaluated no matter the value of myBool
you can also use
Some(someResult).filter(myBool)
Solution 6 - Scala
scala> PartialFunction.condOpt(5) { case x if true => x }
res9: Option[Int] = Some(5)
scala> PartialFunction.condOpt(5) { case x if false => x }
res10: Option[Int] = None
Here, the guard holds the condition and the value passed to condOpt
is the value returned if the guard evaluates to true.
Solution 7 - Scala
Another choice:
implicit class RichOptionCompanion(val self: Option.type) extends AnyVal {
def when[A](cond: Boolean)(value: => A): Option[A] = if(cond) Some(value) else None
}
Usage:
Option.when(foo != "bar") { ... }
Solution 8 - Scala
class RichBool[T](a: Boolean, res:=> T) {
def toOption: Option[T] = if (a) Some(res) else None
}
implicit def boolToRichBool[T](tp: (Boolean, T)): RichBool[T] = new RichBool(tp._1, tp._2);
This would give you:
(true, 5).toOption // Some(5);
(false, 3).toOption // None
Solution 9 - Scala
Here are a couple things I would consider:
val bool: Boolean = ???
val result = 1337
Option(bool).withFilter(identity).map(_ => result)
or
for {
opt <- Option(bool)
if opt
} yield result
Solution 10 - Scala
Option(true).find(_ == true) // Some(true)
Option(false).find(_ == true) // None