我疲惫的Scala技能令我感到困惑的是正确的做事方式。以下代码仅在我包含t match {...
行时编译(并且有效)。如果我消除了那一行,当然还有上一行的诊断println
,我得到了编译时错误,如图所示。显然,编译器将折叠的返回视为单位(对我来说很惊讶)。这可能是合理的,但我不明白。有人请告诉我一个更好的编码方法,也许会给我更多的见解吗?
[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
}
答案 0 :(得分:4)
正如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块,而是评估一个赋值(单位,见here)。