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

2020-05-25 06:44发布

This common pattern feels a bit verbose:

if (condition) 
  Some(result)
else None

I was thinking of using a function to simplify:

def on[A](cond: Boolean)(f: => A) = if (cond) Some(f) else None

This reduces the top example to:

on (condition) { result }

Does something like this exist already? Or is this overkill?

标签: scala
7条回答
再贱就再见
2楼-- · 2020-05-25 07:09

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)
查看更多
登录 后发表回答