steve steve - 1 month ago 17
Scala Question

play/scala , implicit request => what is meaning?

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
{

Answer

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