在play框架(scala)文档(http://www.playframework.com/documentation/2.2.x/ScalaActions)中,它说:
play.api.mvc.Action基本上是一个(play.api.mvc.Request => play.api.mvc.Result)函数,它处理一个请求并生成一个要发送给客户端的结果。 / p>
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
操作返回play.api.mvc.Result值,表示要发送到Web客户端的HTTP响应。在这个例子中,Ok构造一个包含text / plain响应体的200 OK响应。
现在,当我在控制台创建回显val(如上所述)时,我没有得到建议的Result值,而是Action [AnyContent]
scala> play.api.mvc.Action[play.api.mvc.AnyContent] = Action(parser=BodyParser(anyContent))
这里发生了什么?文档中是否有错误?
答案 0 :(得分:4)
事实上,如果您查看Action
的代码:https://github.com/playframework/playframework/blob/master/framework/src/play/src/main/scala/play/api/mvc/Action.scala
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
这会调用apply
的{{1}}方法确实会返回新的Action
:
Action
然后:
/**
* Constructs an `Action` with default content.
*
* For example:
* {{{
* val echo = Action { request =>
* Ok("Got request [" + request + "]")
* }
* }}}
*
* @param block the action code
* @return an action
*/
final def apply(block: R[AnyContent] => Result): Action[AnyContent] =
apply(BodyParsers.parse.anyContent)(block)
事实上,稍后,框架会通过传递/**
* Constructs an `Action`.
*
* For example:
* {{{
* val echo = Action(parse.anyContent) { request =>
* Ok("Got request [" + request + "]")
* }
* }}}
*
* @tparam A the type of the request body
* @param bodyParser the `BodyParser` to use to parse the request body
* @param block the action code
* @return an action
*/
final def apply[A](bodyParser: BodyParser[A])(block: R[A] => Result): Action[A] =
async(bodyParser) { req: R[A] =>
block(req) match {
case simple: SimpleResult => Future.successful(simple)
case async: AsyncResult => async.unflatten
}
}
参数来调用您创建的apply
的其他Action
方法:
Request
例如:
/**
* Invokes this action.
*
* @param request the incoming HTTP request
* @return the result to be sent to the client
*/
def apply(request: Request[A]): Future[SimpleResult]
此方法将返回echo(request)
,即您之前在
Result
我希望我足够清楚!