How to compare the values ​​of the map parameters at once?

Is it possible to match Option[Map[String,String]]for a certain key right away (for example, without nested matches)?

The following snippet: how to do it:

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     
}
+5
source share
3 answers

Of course! Just flatMapthat sh * t !

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

If you are using Scala 2.10, you can add Option:

def lookup(o: Option[Map[String, String]], k: String) =
  o.flatMap(_ get k).fold(BadRequest)(Ok(_))
+9
source
(for (params <- myOption; value <- params.get(key)) yield Ok(value)).getOrElse(BadRequest)
+3
source

, . , , :

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

collect , getOrElse , None, BadRequest.

+1

All Articles