Johnny Everson
Johnny Everson

Reputation: 8601

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     
}

Upvotes: 5

Views: 1434

Answers (3)

IgnisErus
IgnisErus

Reputation: 396

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.

Upvotes: 1

Rex Kerr
Rex Kerr

Reputation: 167901

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

Upvotes: 3

Travis Brown
Travis Brown

Reputation: 139048

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

Upvotes: 9

Related Questions