Scala: Boolean to Option

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

    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.

提交回复
热议问题