Search code examples
scalascala-option

How to match option map values at once?


is it possible to match Option[Map[String,String]] for some key at once (e.g. without nested matches)?

The following snippet is how it is now:

val myOption:Option[Map[String,String]] = ...
myOption match {
  case Some(params) =>
    params get(key) match {
      case Some(value) => Ok(value)
      case None => BadRequest
  case None => BadRequest     
}

Solution

  • Sure! Just flatMap that sh*t!

    def lookup(o: Option[Map[String, String]], k: String) =
      o.flatMap(_ get k).map(Ok(_)).getOrElse(BadRequest)
    

    If you're using Scala 2.10 you can fold over the Option:

    def lookup(o: Option[Map[String, String]], k: String) =
      o.flatMap(_ get k).fold(BadRequest)(Ok(_))