Scala: Boolean to Option

前端 未结 10 1935
一整个雨季
一整个雨季 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 06:02

    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
    

提交回复
热议问题