Reputation: 1747
In
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
It seems Action is a function, have one function type parameter, it's type is Request[A] => Result
In the doc:https://www.playframework.com/documentation/2.7.x/api/scala/play/api/mvc/Action.html
It tell me Action is a trait:
trait Action[A] extends EssentialAction
"An action is essentially a (Request[A] => Result) function that handles a request and generates a result to be sent to the client."
so what the Action really is? a function, or a trait?
Upvotes: 4
Views: 649
Reputation: 48400
In Scala, a function is indeed defined using a trait, for example
object foo extends (Int => String) {
def apply(i: Int): String = s"hello $i"
}
or
val foo: Int => String = i => s"hello $i"
or
val foo = new Function1[Int, String] {
override def apply(i: Int): String = s"hello $i"
}
all define a function we can call with foo(42)
, which desugars to foo.apply(42)
.
An action is
trait Action[A] extends EssentialAction
where EssentialAction
is
trait EssentialAction extends (RequestHeader) => Accumulator[...]
where we see the extends (RequestHeader) => Accumulator
syntax. Note that A => B
is syntactic sugar for Function1
trait, so we could write
trait EssentialAction extends Function1[RequestHeader, Accumulator[...]]`
Now an Action
trait also has an Action
companion object which takes a function argument block
and constructs an Action
with default request body:
Action.apply(block: (Request[AnyContent]) => Result): Action[AnyContent]
and this is in fact what is used when we write
Action { request =>
Ok("Got request [" + request + "]")
}
Upvotes: 8