I'm using Play 2.x and found the following syntax in action handlers eg
object Application extends Controller {
/**
* Index action handler
*/
def index = Action { implicit request =>
Ok(Json.obj("one" -> "two"))
}
}
Here I understand everything except the = Action
which is not the type of the function, because the function return type is play.api.mvc.Result
. So what does the = Action
mean?
To make the understanding worse I now introduced authentication and based on examples changed my Application to:
object Application extends Controller with Secured {
/**
* Index action handler
*/
def index = IsAuthenticated { username => implicit request =>
Ok(Json.obj("one" -> "two"))
}
}
This works but why the Action
is no longer necessary? was it necessary at all? how can I combine several of these types (whatever they mean): Action
or DBAction
, IsAuthenticated
etc?
Action
is not a type, it is a function. If it were a type the signature for index
would look like
def index: Action = { implicit request =>
Notice the addition of the :
and the location of the =
The relevant documentation states an Action is a
function that handles a request and generates a result to be sent to the client
As you noticed you are returning a play.api.mvc.Result
Ok now thanks to a colleague I understood what it is. That syntax that simply means returning an object, in this case an object of type Action
and the action takes as constructor argument a function that takes as input a Request and returns a SimpleResult
, it can be rewritten as eg
object Application extends Controller {
/**
* Index action handler
*/
def index : Action[AnyContent] = {
Action(implicit request => Ok(Json.obj("one" -> "two")))
}
}
What makes it actually confusing is that in Scala they can switch between parenthesis and curly brackets somewhat indistinctly. Therefore makes it tricky to realize it is not a function body what I was looking at but a constructor parameter to an action (which is an anonymous function)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.