如何知道从选项[Map [String,Seq [String]]]包含键还是不是? [英] how to know from Option[Map[String,Seq[String]]] contains key or not?
问题描述
我想知道 request.body.asFormUrlEncoded
是否包含 deviceId
或不。
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
对于选项[Map [String,Seq [String]]]有任何conatins或任何其他函数的方式]
推荐答案
我强烈建议您不要使用 formValues.get(whatever)
,部分是因为语法高度混乱 - 它看起来像你用键参数调用 get
(例如在地图上),当你真的'在选项
上调用 get
(这是一个不安全的操作 - 您应该远离基本上总是在
上选择选项),然后在结果图上应用
应用
。
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.
而是你可以使用 exists
在选项
上与一起包含
。下面是一个稍微简化的例子:
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))
只有当 Option时,才会返回
true
一个更好的方法是避免使用非空的 if
-statement like this:
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 }
这里我们以 Option
是不可用的,则键为空,地图包含该键。
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.
这篇关于如何知道从选项[Map [String,Seq [String]]]包含键还是不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!