Reputation: 607
What language construction is used here to create Action instance? I thought that in Scala it is possible to instantiate a class using:
new Action(params)
apply()
method of companion object (which usually calls constructor): Action(params)
But in the Scaladoc of Play! Action is see following snippet:
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
What is called here? I understand that we create function request => response
, but where is this function passed?
Upvotes: 1
Views: 149
Reputation: 3435
To all said above, for you also would be useful to CTRL + click on the class/method name in your IDE and look in the source code. That sometimes clarifies a lot. Please try and you will see 3 or 4 different variants of apply() methods in the ActionBuilder class.
Upvotes: 0
Reputation: 6423
Basically you are calling the Action companion object's apply method. And as Andreas pointed out during method calls () can be replaced by {} AFAIK.
api doc Action object
def apply(block: (Request[AnyContent]) ⇒ Result): Action[AnyContent]
Action is a subclass of ActionBuilder. It goes to this method call in the play frame work source code.
Upvotes: 2
Reputation:
Your example is equivalent to this:
val echo = Action.apply(request => Ok("Got request [" + request + "]"))
So you're actually calling object Action
's apply
method and pass it an anonymous function.
Be aware that in Scala, you can mostly interchange parentheses and braces, so e.g. if you have this function
def f(a: Int) = a + 42
these calls are equivalent:
f(23)
f { 23 }
The next thing that happens is that you can omit the name of the apply
method. So if you have an object like this:
object f { def apply(a: Int) = a + 42 }
these calls are all equivalent:
f.apply(23)
f.apply { 23 }
f(23)
f { 23 }
f apply 23
f apply { 23 }
Upvotes: 5