Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: problems with return statement

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...

like image 372
opensas Avatar asked Aug 13 '12 06:08

opensas


1 Answers

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.

like image 162
Daniel C. Sobral Avatar answered Oct 18 '22 17:10

Daniel C. Sobral