Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Boolean to Option

Tags:

scala

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.

like image 756
Chris Beach Avatar asked Oct 30 '13 18:10

Chris Beach


2 Answers

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 } 
like image 196
n1r3 Avatar answered Sep 22 '22 02:09

n1r3


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.

like image 37
Xavier Guihot Avatar answered Sep 21 '22 02:09

Xavier Guihot