Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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     
}
like image 518
Johnny Everson Avatar asked Sep 06 '12 13:09

Johnny Everson


2 Answers

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(_))
like image 51
Travis Brown Avatar answered Oct 26 '22 11:10

Travis Brown


(for (params <- myOption; value <- params.get(key)) yield Ok(value)).getOrElse(BadRequest)
like image 44
Rex Kerr Avatar answered Oct 26 '22 11:10

Rex Kerr