I have a Boolean and would like to avoid this pattern:
if (myBool)
Option(someResult)
else
None
What I\'d like to do is
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
}
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
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
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") { ... }
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.
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.