Scala: Boolean to Option

前端 未结 10 1878
一整个雨季
一整个雨季 2021-02-02 05:30

I have a Boolean and would like to avoid this pattern:

if (myBool) 
  Option(someResult) 
else 
  None

What I\'d like to do is



        
10条回答
  •  轮回少年
    2021-02-02 05:36

    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
    }
    

提交回复
热议问题