Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 {

like image 521
kn3l Avatar asked Oct 25 '16 06:10

kn3l


1 Answers

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
like image 57
Yuval Itzchakov Avatar answered Nov 15 '22 03:11

Yuval Itzchakov