Reputation: 22171
As the official documentation of Play framework recommends, we can use an implicit request
in order to improve access to some objects associated to the request.
Sample:
def index = Action { implicit request =>
session.get("connected").map { user =>
Ok("Hello " + user)
}.getOrElse {
Unauthorized("Oops, you are not connected")
}
}
This is due to the addition of the following implicit
method belonged to the Controller
trait:
/**
* Retrieves the session implicitly from the request.
*
* For example:
* {{{
* def index(name:String) = Action { implicit request =>
* val username = session("username")
* Ok("Hello " + username)
* }
* }}}
*/
implicit def session(implicit request: RequestHeader) = request.session
Question: Why does this method is declared itself as implicit
? Isn't it enough to only declare request
parameter as implicit
?
I expected to see that instead:
def session(implicit request: RequestHeader) = request.session
Upvotes: 0
Views: 329
Reputation: 32719
The first implicit
keyword is indeed not necessary at all to allow your sample to compile. So either it is an error in Play!, or the additional implicit
keyword was intended to play another role.
In particular with this additional implicit
keyword, you can call a method that expects an implicit value of type Session
even if you only have an implicit value of type RequestHeader
in scope (session
also defines an implicit value of type RequestHeader
, provided that you have an implicit value of type RequestHeader
in scope).
Upvotes: 1