5

Most of the play framework I see the block of code

// Returns a tasks or an 'ItemNotFound' error
def info(id: Long) = SecuredApiAction { implicit request =>
  maybeItem(Task.findById(id))
}

yes my understanding is define a method info(id: Long) and in scala doc to create function in scala the syntax look like this:

def functionName ([list of parameters]) : [return type] = {
   function body
   return [expr]
}

Can you tell me what is the meaning of implicit request => and SecuredApiAction put before {

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
tree em
  • 20,379
  • 30
  • 92
  • 130

1 Answers1

8

play.api.mvc.Action has helper methods for processing requests and returning results. One if it's apply overloads accepts a play.api.mvc.Request parameter:

def apply(request: Request[A]): Future[Result]

By marking the request parameter as implicit, you're allowing other methods which implicitly require the parameter to use it. It also stated in the Play Framework documentation:

It is often useful to mark the request parameter as implicit so it can be implicitly used by other APIs that need it.

It would be same if you created a method yourself and marked one if it's parameters implicit:

object X {
  def m(): Unit = {
    implicit val myInt = 42
    y()
  }

  def y()(implicit i: Int): Unit = {
    println(i)
  }
}

Because there is an implicit in scope, when invoking y() the myInt variable will be implicitly passed to the method.

scala> :pa
// Entering paste mode (ctrl-D to finish)

object X {
  def m(): Unit = {
    implicit val myInt = 42
    y()
  }

  def y()(implicit i: Int): Unit = {
    println(i)
  }
}

// Exiting paste mode, now interpreting.

defined object X

scala> X.m()
42
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Thank you for great explaination, and SecuredApiAction put before `{` is like an anotation of body expression ? – tree em Oct 25 '16 at 06:39
  • still not get your point about this, could more explain on this point, I appreciate your answer. – tree em Oct 25 '16 at 06:47
  • @steve Where is `SecuredApiAction` defined? Is it a custom class you made? – Yuval Itzchakov Oct 25 '16 at 06:48
  • the source I am learning from here https://github.com/adrianhurt/play-api-rest-seed/blob/master/app/controllers/Folders.scala the function define here: https://github.com/adrianhurt/play-api-rest-seed/blob/master/app/api/ApiController.scala – tree em Oct 25 '16 at 06:53
  • 1
    @steve [`SecureApiAction` is a method](https://github.com/adrianhurt/play-api-rest-seed/blob/master/app/api/ApiController.scala#L33) which accepts an argument of type `action: SecuredApiRequest[Unit] => Future[ApiResult]`. In Scala, you can invoke a method with curly brackets `{ }` or with round brackets `( )`. – Yuval Itzchakov Oct 25 '16 at 07:00
  • I understood now,thank you so much. – tree em Oct 25 '16 at 07:02
  • @steve You welcome :) – Yuval Itzchakov Oct 25 '16 at 07:02