Idiomatic Scala: display options depending on the condition

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?

+4
source share
5

Option.collect:

a scala.Some, pf scala.Option , , pf - .

val result = option.collect {
  case x if condition => valueToResult(x)
}.getOrElse(defaultResult)
+9
val result = option match {
  case Some(value) if condition => valueToResult(value)
  case _ => defaultResult
}
+3
val result = (for (v<-option if condition) yield valueToResult(v)).getOrElse(defaultResult)
+1
source
option.foldLeft(defaultResult)((d,x) => if (condition) valueToResult(x) else d)
+1
source
val result = (condition match {
  case true => option.map(valueToResult)
  case false => None
}).getOrElse(defaultResult)
0
source

Source: https://habr.com/ru/post/1655152/


All Articles