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