Return 类型 bindFromRequest.fold

Return type of bindFromRequest.fold

我微弱的 Scala 技能让我对做某事的正确方法感到困惑。仅当我包含 t match {... 行时,下面的代码才能编译(并运行)。如果我删除该行,当然还有前一行的诊断 println,我会得到如图所示的编译时错误。显然,编译器将折叠的 return 视为单位(令我感到惊讶)。这可能是合理的,但我不明白。有人能告诉我一个更好的编码方法吗,也许能给我更多的见识?

[error] /home/bill/activator/cherry/app/controllers/Application.scala:34: type mismatch;
[error]  found   : Unit
[error]  required: play.api.mvc.Result
[error]   }
[error]   ^

来源:

  def ptweets = Action { implicit request =>
    import play.api.data._
    val rqForm = Form(Forms.mapping(
      "k" -> Forms.number,
      "who" -> Forms.text,
      "what" -> Forms.text)(TweetInquiry.apply)(TweetInquiry.unapply))
    val t = rqForm.bindFromRequest.fold(
      formWithErrors => BadRequest("That's not good"),
      rq =>  Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>"))))
    ) // expect a play.api.mvc.Result
    println(t.getClass.getName) // this confirms it in both run-time cases
    t match { case v:Result => v } // yet this is required for compile
  }

如评论中m-z所说,改变

val t = rqForm.bindFromRequest.fold(
      formWithErrors => BadRequest("That's not good"),
      rq =>  Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>"))))
    ) // expect a play.api.mvc.Result
    println(t.getClass.getName) // this confirms it in both run-time    cases
    t match { case v:Result => v } // yet this is required for compile

只是:

rqForm.bindFromRequest.fold(
      formWithErrors => BadRequest("That's not good"),
      rq =>  Ok((views.html.properForm("POST tweets TBD.")(Html("<em>Blah</em>"))))
   )

折叠正在评估结果,但在您发布的代码中,您将该结果分配给值 t。因此,不是 Action 块计算折叠的结果,而是计算一个赋值(即 Unit,参见 here)。