This common pattern feels a bit verbose:
if (condition)
Some(result)
else None
I was thinking of using a function to simplify:
Here is another approach that is quite straightforward:
Option(condition).collect{ case true => result }
A simple example:
scala> val enable = true
enable: Boolean = true
scala> Option(enable).collect{case true => "Yeah"}
res0: Option[String] = Some(Yeah)
scala> Option(!enable).collect{case true => "Yeah"}
res1: Option[String] = None
Here some advanced non-Boolean examples that put the condition into the pattern match:
val param = "beta"
Option(param).collect{case "alpha" => "first"} // gives None
Option(param).collect{case "alpha" => "first"
case "beta" => "second"
case "gamma" => "third"} // gives Some(second)
val number = 999
Option(number).collect{case 0 => "zero"
case x if x > 10 => "too high"} // gives Some(too high)