Question

What is the more idiomatic way to handle an Option, map / getOrElse, or match?

val x = option map {
  value => Math.cos(value) + Math.sin(value)
} getOrElse {
  .5
}

or

val x = option match {
    case Some(value) => Math.cos(value) + Math.sin(value)
    case None => .5
}
Was it helpful?

Solution

You could always just look at the Scaladoc for Option:

The most idiomatic way to use an scala.Option instance is to treat it as a collection or monad and use map,flatMap, filter, or foreach:

val name: Option[String] = request getParameter "name"
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper getOrElse "")

And a bit later:

A less-idiomatic way to use scala.Option values is via pattern matching:

val nameMaybe = request getParameter "name"
nameMaybe match {
  case Some(name) =>
    println(name.trim.toUppercase)
  case None =>
    println("No name value")
}

OTHER TIPS

Use fold for this kind of map-or-else-default thing:

val x = option.fold(0.5){ value => Math.cos(value) + Math.sin(value) }

Obviously both are valid and I don't think one is more idiomatic than the other. That being said, using map uses the fact the Option is a Monad. This can be particularly advantageous when combining two Options. Say you have two Option[Int] that you would like to add. In this case instead of doing multiple matches it is much cleaner to use map/flatMap and it's equivalent "for comprehensions". So for your example both are valid... but for other examples using map/flatMap is often much more succinct.

Some(6).flatMap(intValue => Some(5).map(intValue + _))

or

for {
   i <- Some(6)
   j <- Some(5)
} yield i + j

All of them have different semantics, so in your case none of them.

map applies some function to the value inside Option, if it exists (Some, not None). Basically this is how you safely work with Options, appling function on some null value is dangeroues, cause it can throw NPE, but in case with Option it just returns None.

getOrElse simply returns either it's value or default one (which you provide as an argument). It won't do anything with the value inside the Option, you can just extract it, if you have Some, or return a default one, in case of None.

and match approach i'd say is a combination of two, cause you can apply some computation on the values and extract it from the Option

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top