netzwerg netzwerg - 1 year ago 85
Scala Question

Idiomatic Scala: Mapping over option depending on condition

I have two

s, a
and an
. Note that
is a simple boolean, not depending on the option's value.

holds true, I would like to map over the option to convert it to a result value. In all other cases, I would like to return a

This works and is quite readable, but I dislike the duplication of

val result = if (condition) {
} else {

My second approach does not have duplications, but I dislike the fact that filter is abused for something that is not actually dependent on the option's value:

val result = option.filter(_ => condition).map(valueToResult).getOrElse(defaultResult)

What's a more idiomatic or otherwise better approach in Scala?

Answer Source

You can use Option.collect:

Returns a scala.Some containing the result of applying pf to this scala.Option's contained value, if this option is nonempty and pf is defined for that value.

val result = option.collect {
  case x if condition => valueToResult(x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download