Explicit return from play action

前端 未结 2 1153
心在旅途
心在旅途 2020-12-10 23:36

I have following action

def login: Result = Action(parse.json) { request =>
  if (/* Let\'s we say here is some validation */) {
    return BadRequest(\"b         


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 00:04

    You cannot use return in this context because the Scala compiler misinterprets what you mean by return. You intended for the return to return from the function that is being passed to Action.apply, i.e. this block:

    { request =>
      if (/* Let's we say here is some validation */) {
        return BadRequest("bad")
      }
    
      Ok("all ok")
    }
    

    However, in Scala return cannot be used to return from functions, only methods. Any return is interpreted as returning from the nearest enclosing method. In this case, the compiler thought you were returning from login.

    You have the wrong type on login. login should be a Action[JsValue]. With that correct type, the compiler will complain about the return because you are returning a SimpleResult instead of the expected Action[JsValue]. With the incorrect type Result, the compiler accepts the return but then isn't happy because the return value of Action.apply is always a type of Action.

    The reason return works this way is to support loops like:

    def allPositive(l: List[Int]): Boolean = {
      l.foreach { x => if (x < 0) return false }
      true
    }
    

    But using return is unidiomatic. The return in the above loop is implemented with exception throwing so it is inefficient. And return can make for very confusing code:

    def login: Result = Action(parse.json) { request =>
      /*
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL with return  OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE WALL OF CODE
      */
    
      Ok("all ok")
    }
    

    Obviously this login always returns Ok. Oh wait...there is a return buried in there.

提交回复
热议问题