Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know from Option[Map[String,Seq[String]]] contains key or not?

I want to know the request.body.asFormUrlEncoded contains deviceId or not.

val formValues=request.body.asFormUrlEncoded
val number = formValues.get("mobile").head
var deviceId ="deviceIdNotFound"
if(condtion) //thats the problem
deviceId= formValues.get("deviceId").head

is there any way of conatins or any other function for Option[Map[String,Seq[String]]]

like image 580
Govind Singh Avatar asked Jun 13 '14 12:06

Govind Singh


1 Answers

I'd strongly encourage you not to use formValues.get("whatever"), in part because the syntax is highly confusing—it looks like you're calling get with a key argument (as for example on a map), when really you're calling get on the Option (which is an unsafe operation—you should stay away from get on Option basically always) and then apply on the resulting map (also unsafe). This muddle is Scala's fault, not yours, but you still want to avoid stepping in it.

Instead you can use exists on the Option together with contains on the map. Here's a slightly simplified example:

val containsKey = formValues.exists(_.contains(key))

This will return true only if the Option is non-empty and the map it contains has the key.

An even better approach is to avoid the if-statement like this:

val os: Option[Seq[String]] = for {
  m <- formValues
  v <- m.get(key)
} yield v

os.foreach { v => \\ do something with the value }

Here we end up with an Option that contains the value pointed to by key if the original Option is non-empty and the map contains that key.

like image 135
Travis Brown Avatar answered Sep 21 '22 23:09

Travis Brown