Scala Option offers two different ways to handle an Option value.
Option.map/getOrElse
val name: Option[String] = request getParameter "name" name map { _.toUpperCase } getOrElse ""
Option.fold
val name: Option[String] = request getParameter "name" name.fold("") { _.toUpperCase }
On the spark-dev mailing list, there was a discussion on using Option.fold instead of Option.map/getOrElse combination.
Two idioms look almost the same, but people seem to prefer one over the other for readability reasons. Here is the summary of the discussion:
- Option.getOrElse/map is a more idiomatic Scala code because Option.fold was only introduced in Scala 2.10.
- Fold on Option is not obvious to most developers.
- Option.fold is not readable.
- Reverses the order of Some vs None.
- Putting the default condition first there makes it not as intuitive.
- When code gets long, the lack of an obvious boundary with two closures is confusing. (“} {” compared to getOrElse)
- Fold is a more functional idiom in general.
It seems people are getting used to functional idioms such as map and filter, but still are reluctant to accept more functional idioms such as Option.fold.
I prefer Option.getOrElse/map because I think putting the default value first is not intuitive and much of Scala code is already written with Option.getOrElse/map. However, both options are fine as long as only one style is used through the project. Consistency is more important than taste!