0

I try to get the payload from a POST in Play 2.3.

Therefore I use this expression.

val name = request.body.asFormUrlEncoded.get("name").flatMap(_.headOption)

But I run into trouble, when the field "name" is not present. Using the debugger, I can see that request.body.asFormUrlEncoded is of type Some(Map) or ListMap? I'm not sure, in the debugger both terms are displayed. When the field "name" exists, everything is fine, but if the field "name" is missing, it throws an NoSuchElementException.

I can see that only calling request.body.asFormUrlEncoded.get("name") does return an ArrayBuffer. But shouldn't it return a Some(ArrayBuffer) and a None in case of "name" field is not existing?

So what can I do to query the value of a field without generating an exception if the field is missing.

Added: Here is the declaration of AnyContentAsFormUrlEncoded. So it's a Map. But get on a Map should return Some or None, but not directly the object.

case class AnyContentAsFormUrlEncoded(data: Map[String, Seq[String]]) extends AnyContent
4

1 回答 1

3

您在这里遇到了 Scala 限制:

对 .get 函数的调用是在你的 .get 上完成的Option[Map[String, Seq[String]],然后你使用("name")它被翻译成.apply("name"). 如果键不在地图中,您实际上是在调用可能引发异常apply的对象。Map

为避免这种情况,您可以使用:

val name: Option[String] = request.body.asFormUrlEncoded.flatMap(m => m.get("name").flatMap(_.headOption))
于 2014-06-20T14:59:01.007 回答