Simplify if (x) Some(y) else None?

后端 未结 7 1887
旧时难觅i
旧时难觅i 2021-02-05 02:46

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

I was thinking of using a function to simplify:



        
7条回答
  •  借酒劲吻你
    2021-02-05 03:13

    You can use the PartialFunction companion object and condOpt:

    PartialFunction.condOpt(condition) {case true => result}
    

    Usage:

     scala> PartialFunction.condOpt(false) {case true => 42}
     res0: Option[Int] = None
    
     scala> PartialFunction.condOpt(true) {case true => 42}
     res1: Option[Int] = Some(42)
    

提交回复
热议问题