9

I have a Play 2.0 app

TestController.scala

def foo(p1: String) = Action {implicit request =>
  Ok(bar(p1))
}

private def bar(p1: String) = {
//access request parameter here
}

Is there a way to use implicit to pass request to bar

biesior
  • 55,576
  • 10
  • 125
  • 182
Bob
  • 8,424
  • 17
  • 72
  • 110

1 Answers1

18

Yes, you can:

  def foo(p1: String) = Action { implicit request =>
    Ok(bar(p1))
  }

  private def bar(p1: String)(implicit req: RequestHeader) = "content"

The code:

Action { implicit request

Calls this method on the Action object:

def apply(block: Request[AnyContent] => Result): Action[AnyContent] = {

So, what you called "request" matches the paramater named "block". The "implicit" here is optional: it makes the "request" value available as an implicit parameter to other method/function calls.

The implicit in your "bar" function says that it can take the value of "req" from an implicit value, and doesn't necessarily need to be passed in explicitly.

Adam Rabung
  • 5,232
  • 2
  • 27
  • 42
  • Thanks Adam, that works. Follow up question, does the implicit need to be passed as a curried parameter? – Bob Jun 26 '12 at 17:44
  • 1
    In scala, it the the parameter _list_, not the parameter, that is implicit. I'm not sure of the motivation for that. – Adam Rabung Jun 26 '12 at 19:34
  • 1
    scala> implicit val i = 1 i: Int = 1 scala> implicit val s = "hi" s: java.lang.String = hi scala> def concat(implicit x:Int, y:String) = x + y concat: (implicit x: Int, implicit y: String)String scala> concat res0: String = 1hi – Adam Rabung Jun 26 '12 at 19:35
  • With play 2.0.3 I kept getting "Cannot find any HTTP Request here" when I did `def foo[A](i: Int)(implicit request: Request[A]): Baz = { ... }`. This error was fixed by changing `Request[A]` to instead use `RequestHeader`. Thanks Adam Rabung- your info was a big help. – Jay Taylor Aug 29 '12 at 00:14
  • With play 2.4.6, I need to use Request[AnyContent] – code4j Jan 01 '16 at 19:33