Scala: Boolean to Option

前端 未结 10 1753
一整个雨季
一整个雨季 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:48

    scala> PartialFunction.condOpt(5) { case x if true => x }
    res9: Option[Int] = Some(5)
    
    scala> PartialFunction.condOpt(5) { case x if false => x }
    res10: Option[Int] = None
    

    Here, the guard holds the condition and the value passed to condOpt is the value returned if the guard evaluates to true.

提交回复
热议问题