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

后端 未结 7 1889
旧时难觅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:21

    You could create the Option first and filter on that with your condition:

    Option(result).filter(condition)
    

    or if condition is not related to result

    Option(result).filter(_ => condition)
    

提交回复
热议问题