Question

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     
}
Was it helpful?

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(_))

OTHER TIPS

(for (params <- myOption; value <- params.get(key)) yield Ok(value)).getOrElse(BadRequest)

You should be able to do this using a couple of higher-order functions. I think this does what you want:

myOption.collect {
  case m if (m contains key) => Ok(m(key))
} getOrElse BadRequest

collect takes a partial function, and the getOrElse handles the case where the partial function returned None, which translates it to your BadRequest case.

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