Scala: Boolean to Option

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

    Option().collect() is a good pattern for this kind of thing.

    Option(myBool).collect { case true => someResult }
    

    from the REPL:

    scala> (Option(true).collect { case true => 3 }, Option(false).collect { case true => 3 })
    res3: (Option[Int], Option[Int]) = (Some(3),None)
    

提交回复
热议问题