I have two vals, a conditionand option. Note that it conditionis a simple Boolean, independent of the parameter value.
If conditiontrue, I would like to map the option to convert it to the result value. In all other cases, I would like to return defaultResult.
This works and is quite readable, but I don't like duplication defaultResult:
val result = if (condition) {
option.map(valueToResult).getOrElse(defaultResult)
} else {
defaultResult
}
There is no duplicate in my second approach, but I don’t like the fact that the filter abuses that it doesn’t really depend on the parameter value:
val result = option.filter(_ => condition).map(valueToResult).getOrElse(defaultResult)
Which more idiomatic or different approach is better for Scala?
source
share