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?
Similar to Scalaz, the Typelevel cats ecosystem has the mouse package with
option
:You can use the
PartialFunction
companion object andcondOpt
:Usage:
Starting
Scala 2.13
,Option
is now provided with thewhen
builder which does just that:For instance:
Also note the coupled
unless
method which does the opposite.Scalaz includes the option function:
Here is another approach that is quite straightforward:
A simple example:
Here some advanced non-Boolean examples that put the condition into the pattern match: