【问题标题】:Play Framework/Scala: "return" statement in Action?Play Framework/Scala:“return”语句在行动?
【发布时间】:2015-02-10 19:41:43
【问题描述】:

我知道这不是 Scala 的写法。我认为,在 Scala 中你会使用 map.但我想这样写,因为它更像 Java/c++。 但是编写以下代码,Scala 编译器会抱怨“方法 addGroup 具有返回语句;需要结果类型”。 省略返回并使用 else 分支有效。但是出于格式化的原因,我想使用返回,因为我不想缩进如果你使用“else {}”会发生的其余代码。

在哪里添加结果类型。 “Future[Result]”是正确的类型吗?

def addGroup = Action { implicit request =>
  val optionUser = GetUserFromSession(request)
  if (optionUser == None) {
    return Redirect(routes.ApplicationUser.show(0))
  }
  Redirect(routes.ApplicationUser.show(optionUser.get.id))
}

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    你不能。 Action.apply 的主体是一个匿名函数,您试图过早地从中返回。问题是,Scala 中的 return 关键字从最内层的 named 方法返回,这肯定不是。因此,您将尝试返回一个 Result,该方法需要一个 Action[A]

    唯一可行的方法是拆分功能:

    def addGroup = Action { implicit request =>
      result(request)
    }
    
    // Could have a better name, but whatever, you shouldn't do this.
    def result(request: Request): Result = {
      val optionUser = GetUserFromSession(request)
      if (optionUser == None) {
        return Redirect(routes.ApplicationUser.show(0))
      }
      Redirect(routes.ApplicationUser.show(optionUser.get.id))
    }
    

    使用return 会使代码怪异且难以阅读,所以请不要使用。

    如果保存单个缩进确实是一个问题,那该怎么办?

    def addGroup = Action { implicit request =>
      val optionUser = GetUserFromSession(request)
      if (optionUser == None) Redirect(routes.ApplicationUser.show(0))
      else Redirect(routes.ApplicationUser.show(optionUser.get.id))
    }
    

    就我个人而言,我会用mapgetOrElse 重写这个:

    def addGroup = Action { implicit request =>
      GetUserFromSession(request) map { user =>
         Redirect(routes.ApplicationUser.show(user.id))
      } getOrElse {
         Redirect(routes.ApplicationUser.show(0))
      }     
    }
    

    它消除了使用.get 的需要,并且还优先考虑了正分支。

    【讨论】:

    • 这可能是个人喜好,但我发现使用 return 可以大大降低大括号的级别,即使它在 Scala 中可能不常见。无论如何,如果不可能,我必须忍受额外的缩进。
    • @bebo 我编辑中的if/else 会更容易接受吗?
    • 仅将我的示例视为一个非常简单的示例。我已经使用了 if/else 和 .map 结构。但是我想使用 return 方法的原因是,如果你有,比如说,在开始渲染最终的 html 文档之前要测试 5 个条件,你会得到 5 个大括号和 5 个缩进。如果您有 5 个或更多 if/else 或 .map,那么您将拥有与条件一样多的缩进。如果您使用 return,则 Action 的主要部分(实际上是构建内容),在我的示例中只有第二个 Redirect,将不会缩进,并且您不会在它们周围得到无数的大括号。
    猜你喜欢
    • 2015-11-10
    • 2011-04-15
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多