Scala: Boolean to Option

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

    Here are a couple things I would consider:

    val bool: Boolean = ???
    val result = 1337    
    
    Option(bool).withFilter(identity).map(_ => result)
    

    or

    for {
      opt <- Option(bool)
      if opt
    } yield result
    

提交回复
热议问题