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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With