Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic Scala: Mapping over option depending on condition

Tags:

scala

I have two vals, 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?

like image 614
Rahel Lüthy Avatar asked Dec 08 '22 21:12

Rahel Lüthy


2 Answers

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)
like image 107
Yuval Itzchakov Avatar answered Jan 10 '23 23:01

Yuval Itzchakov


val result = option match {
  case Some(value) if condition => valueToResult(value)
  case _ => defaultResult
}
like image 24
Rahel Lüthy Avatar answered Jan 10 '23 22:01

Rahel Lüthy