Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle Scala Option idiomatically

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
}
like image 327
Paul Draper Avatar asked Jan 30 '14 21:01

Paul Draper


2 Answers

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")
}
like image 76
Vidya Avatar answered Sep 27 '22 19:09

Vidya


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

val x = option.fold(0.5){ value => Math.cos(value) + Math.sin(value) }
like image 41
dhg Avatar answered Sep 27 '22 21:09

dhg