Search code examples
scalascala-option

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
}

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")
    }