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

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)

Scalaz includes the option function:

import scalaz.syntax.std.boolean._

true.option("foo") // Some("foo")
false.option("bar") // None

Starting Scala 2.13, Option is now provided with the when builder which does just that:

Option.when(condition)(result)

For instance:

Option.when(true)(45)
// Option[Int] = Some(45)
Option.when(false)(45)
// Option[Int] = None

Also note the coupled unless method which does the opposite.

Tags:

Scala