I'm a little puzzled wth this
The following code compiles ok:
def save: Action[AnyContent] = Action {
if (1 == 2) {
BadRequest(toJson("something went wrong"))
} else {
Ok(toJson(Feature.find))
}
}
but if I just add the return statement, I get the following:
def save: Action[AnyContent] = Action {
if (1 == 2) {
return BadRequest(toJson("something went wrong"))
} else {
return Ok(toJson(Feature.find))
}
}
[error] found : play.api.mvc.SimpleResult[play.api.libs.json.JsValue]
[error] required: play.api.mvc.Action[play.api.mvc.AnyContent]
[error] return BadRequest(toJson("something went wrong"))
I thought this two codes would be equivalent...
BTW, Action is a companion object, with an apply method that receives a function of the form: Request[AnyContent] => Result, and that returns an Action[AnyContent]
It seems like with the return statement, the block is returning the result of directly executing BadRequest... and Ok... instead of returning the result of passing the block to the Action object companion...
Am I right?
Note: I'm trying to find a way of getting rid of so many nested map and getOrElse
ps: sorry if the question is a little confuse, I'm confused myself...
These two expressions do very different things indeed!
def save: Action[AnyContent] = Action {
if (1 == 2) {
BadRequest(toJson("something went wrong"))
} else {
Ok(toJson(Feature.find))
}
}
Here, save
will return the result of Action(Ok(toJson(Feature.find)))
. Now,
def save: Action[AnyContent] = Action {
if (1 == 2) {
return BadRequest(toJson("something went wrong"))
} else {
return Ok(toJson(Feature.find))
}
}
The situation here is more complicated. When return Ok(toJson(Feature.find))
is evaluated, it will return from save
! That is, Ok(toJson(Feature.find))
will not be passed to Action
. Instead, the execution of the method save
will stop and Ok(toJson(Feature.find))
will be returned as its result -- except that this is not the type save
is supposed to return, so it gives a type error.
Remember: return
returns from the enclosing def
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With