netzwerg netzwerg - 2 months ago 7
Scala Question

Idiomatic Scala: Mapping over option depending on condition

I have two

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

If
condition
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
defaultResult
.

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

val result = if (condition) {
option.map(valueToResult).getOrElse(defaultResult)
} else {
defaultResult
}


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

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)
}.getOrElse(defaultResult)
Comments