Reputation: 18918
As someone new to Scala, can someone explain the code here?
val echo = Action { request =>
Ok("Got request [" + request + "]")
}
So I get that you're creating a new value called echo, from an Action trait (similar to a Java interface from what I can gather). request
is some sort of argument, though I've never seen this syntax before -- what do the brackets and arrow =>
signify?
I see that I create a Result
object signifying a 200 response, and presumably returning that. But what sort of function am I returning from? A constructor?
Upvotes: 1
Views: 268
Reputation: 350
An Action is a function that takes a request and yields a result (response). Within the expression {}
you have a function literal (anonymous function) request => Ok()
. Thus, request
will be available within the body after the =>
.
Since this is Scala, the last bit of the expression evaluated will be the result; that is, what's inside Ok()
will be evaluated and then you the result will be generated.
Upvotes: 1
Reputation: 3398
First off, the new value echo is getting its value from the result of calling the function Action.apply
, where Action
is an object (scala singleton, sort of related to statics in Java).
The Action.apply function apparently takes, as its argument, a function and by convention would return a value of the type of the Action trait.
{ request =>
Ok("Got request [" + request + "]")
}
Is a function from some type (the argument is labelled request
) to some type (the return of the call to Ok
).
Assuming you are coming from a Java background, the Java 8 lambdas use a very similar syntax.
Upvotes: 2