I have a Boolean and would like to avoid this pattern:
if (myBool)
Option(someResult)
else
None
What I\'d like to do is
Option(true).find(_ == true) // Some(true)
Option(false).find(_ == true) // None
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)
If you don't mind someResult
being evaluated no matter the value of myBool
you can also use
Some(someResult).filter(myBool)
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